home *** CD-ROM | disk | FTP | other *** search
/ PC World Komputer 2010 April / PCWorld0410.iso / hity wydania / Ubuntu 9.10 PL / karmelkowy-koliberek-9.10-netbook-remix-PL.iso / casper / filesystem.squashfs / usr / share / pyshared / feedparser.py < prev    next >
Text File  |  2009-07-15  |  123KB  |  2,869 lines

  1. #!/usr/bin/env python
  2. """Universal feed parser
  3.  
  4. Handles RSS 0.9x, RSS 1.0, RSS 2.0, CDF, Atom 0.3, and Atom 1.0 feeds
  5.  
  6. Visit http://feedparser.org/ for the latest version
  7. Visit http://feedparser.org/docs/ for the latest documentation
  8.  
  9. Required: Python 2.1 or later
  10. Recommended: Python 2.3 or later
  11. Recommended: CJKCodecs and iconv_codec <http://cjkpython.i18n.org/>
  12. """
  13.  
  14. __version__ = "4.1"# + "$Revision: 1.92 $"[11:15] + "-cvs"
  15. __license__ = """Copyright (c) 2002-2006, Mark Pilgrim, All rights reserved.
  16.  
  17. Redistribution and use in source and binary forms, with or without modification,
  18. are permitted provided that the following conditions are met:
  19.  
  20. * Redistributions of source code must retain the above copyright notice,
  21.   this list of conditions and the following disclaimer.
  22. * Redistributions in binary form must reproduce the above copyright notice,
  23.   this list of conditions and the following disclaimer in the documentation
  24.   and/or other materials provided with the distribution.
  25.  
  26. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS 'AS IS'
  27. AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
  28. IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
  29. ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE
  30. LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
  31. CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
  32. SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
  33. INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
  34. CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
  35. ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
  36. POSSIBILITY OF SUCH DAMAGE."""
  37. __author__ = "Mark Pilgrim <http://diveintomark.org/>"
  38. __contributors__ = ["Jason Diamond <http://injektilo.org/>",
  39.                     "John Beimler <http://john.beimler.org/>",
  40.                     "Fazal Majid <http://www.majid.info/mylos/weblog/>",
  41.                     "Aaron Swartz <http://aaronsw.com/>",
  42.                     "Kevin Marks <http://epeus.blogspot.com/>"]
  43. _debug = 0
  44.  
  45. # HTTP "User-Agent" header to send to servers when downloading feeds.
  46. # If you are embedding feedparser in a larger application, you should
  47. # change this to your application name and URL.
  48. USER_AGENT = "UniversalFeedParser/%s +http://feedparser.org/" % __version__
  49.  
  50. # HTTP "Accept" header to send to servers when downloading feeds.  If you don't
  51. # want to send an Accept header, set this to None.
  52. ACCEPT_HEADER = "application/atom+xml,application/rdf+xml,application/rss+xml,application/x-netcdf,application/xml;q=0.9,text/xml;q=0.2,*/*;q=0.1"
  53.  
  54. # List of preferred XML parsers, by SAX driver name.  These will be tried first,
  55. # but if they're not installed, Python will keep searching through its own list
  56. # of pre-installed parsers until it finds one that supports everything we need.
  57. PREFERRED_XML_PARSERS = ["drv_libxml2"]
  58.  
  59. # If you want feedparser to automatically run HTML markup through HTML Tidy, set
  60. # this to 1.  Requires mxTidy <http://www.egenix.com/files/python/mxTidy.html>
  61. # or utidylib <http://utidylib.berlios.de/>.
  62. TIDY_MARKUP = 0
  63.  
  64. # List of Python interfaces for HTML Tidy, in order of preference.  Only useful
  65. # if TIDY_MARKUP = 1
  66. PREFERRED_TIDY_INTERFACES = ["uTidy", "mxTidy"]
  67.  
  68. # ---------- required modules (should come with any Python distribution) ----------
  69. import sgmllib, re, sys, copy, urlparse, time, rfc822, types, cgi, urllib, urllib2
  70. try:
  71.     from cStringIO import StringIO as _StringIO
  72. except:
  73.     from StringIO import StringIO as _StringIO
  74.  
  75. # ---------- optional modules (feedparser will work without these, but with reduced functionality) ----------
  76.  
  77. # gzip is included with most Python distributions, but may not be available if you compiled your own
  78. try:
  79.     import gzip
  80. except:
  81.     gzip = None
  82. try:
  83.     import zlib
  84. except:
  85.     zlib = None
  86.  
  87. # If a real XML parser is available, feedparser will attempt to use it.  feedparser has
  88. # been tested with the built-in SAX parser, PyXML, and libxml2.  On platforms where the
  89. # Python distribution does not come with an XML parser (such as Mac OS X 10.2 and some
  90. # versions of FreeBSD), feedparser will quietly fall back on regex-based parsing.
  91. try:
  92.     import xml.sax
  93.     xml.sax.make_parser(PREFERRED_XML_PARSERS) # test for valid parsers
  94.     from xml.sax.saxutils import escape as _xmlescape
  95.     _XML_AVAILABLE = 1
  96. except:
  97.     _XML_AVAILABLE = 0
  98.     def _xmlescape(data):
  99.         data = data.replace('&', '&')
  100.         data = data.replace('>', '>')
  101.         data = data.replace('<', '<')
  102.         return data
  103.  
  104. # base64 support for Atom feeds that contain embedded binary data
  105. try:
  106.     import base64, binascii
  107. except:
  108.     base64 = binascii = None
  109.  
  110. # cjkcodecs and iconv_codec provide support for more character encodings.
  111. # Both are available from http://cjkpython.i18n.org/
  112. try:
  113.     import cjkcodecs.aliases
  114. except:
  115.     pass
  116. try:
  117.     import iconv_codec
  118. except:
  119.     pass
  120.  
  121. # chardet library auto-detects character encodings
  122. # Download from http://chardet.feedparser.org/
  123. try:
  124.     import chardet
  125.     if _debug:
  126.         import chardet.constants
  127.         chardet.constants._debug = 1
  128. except:
  129.     chardet = None
  130.  
  131. # ---------- don't touch these ----------
  132. class ThingsNobodyCaresAboutButMe(Exception): pass
  133. class CharacterEncodingOverride(ThingsNobodyCaresAboutButMe): pass
  134. class CharacterEncodingUnknown(ThingsNobodyCaresAboutButMe): pass
  135. class NonXMLContentType(ThingsNobodyCaresAboutButMe): pass
  136. class UndeclaredNamespace(Exception): pass
  137.  
  138. sgmllib.tagfind = re.compile('[a-zA-Z][-_.:a-zA-Z0-9]*')
  139. sgmllib.special = re.compile('<!')
  140. sgmllib.charref = re.compile('&#(x?[0-9A-Fa-f]+)[^0-9A-Fa-f]')
  141.  
  142. SUPPORTED_VERSIONS = {'': 'unknown',
  143.                       'rss090': 'RSS 0.90',
  144.                       'rss091n': 'RSS 0.91 (Netscape)',
  145.                       'rss091u': 'RSS 0.91 (Userland)',
  146.                       'rss092': 'RSS 0.92',
  147.                       'rss093': 'RSS 0.93',
  148.                       'rss094': 'RSS 0.94',
  149.                       'rss20': 'RSS 2.0',
  150.                       'rss10': 'RSS 1.0',
  151.                       'rss': 'RSS (unknown version)',
  152.                       'atom01': 'Atom 0.1',
  153.                       'atom02': 'Atom 0.2',
  154.                       'atom03': 'Atom 0.3',
  155.                       'atom10': 'Atom 1.0',
  156.                       'atom': 'Atom (unknown version)',
  157.                       'cdf': 'CDF',
  158.                       'hotrss': 'Hot RSS'
  159.                       }
  160.  
  161. try:
  162.     UserDict = dict
  163. except NameError:
  164.     # Python 2.1 does not have dict
  165.     from UserDict import UserDict
  166.     def dict(aList):
  167.         rc = {}
  168.         for k, v in aList:
  169.             rc[k] = v
  170.         return rc
  171.  
  172. class FeedParserDict(UserDict):
  173.     keymap = {'channel': 'feed',
  174.               'items': 'entries',
  175.               'guid': 'id',
  176.               'date': 'updated',
  177.               'date_parsed': 'updated_parsed',
  178.               'description': ['subtitle', 'summary'],
  179.               'url': ['href'],
  180.               'modified': 'updated',
  181.               'modified_parsed': 'updated_parsed',
  182.               'issued': 'published',
  183.               'issued_parsed': 'published_parsed',
  184.               'copyright': 'rights',
  185.               'copyright_detail': 'rights_detail',
  186.               'tagline': 'subtitle',
  187.               'tagline_detail': 'subtitle_detail'}
  188.     def __getitem__(self, key):
  189.         if key == 'category':
  190.             return UserDict.__getitem__(self, 'tags')[0]['term']
  191.         if key == 'categories':
  192.             return [(tag['scheme'], tag['term']) for tag in UserDict.__getitem__(self, 'tags')]
  193.         realkey = self.keymap.get(key, key)
  194.         if type(realkey) == types.ListType:
  195.             for k in realkey:
  196.                 if UserDict.has_key(self, k):
  197.                     return UserDict.__getitem__(self, k)
  198.         if UserDict.has_key(self, key):
  199.             return UserDict.__getitem__(self, key)
  200.         return UserDict.__getitem__(self, realkey)
  201.  
  202.     def __setitem__(self, key, value):
  203.         for k in self.keymap.keys():
  204.             if key == k:
  205.                 key = self.keymap[k]
  206.                 if type(key) == types.ListType:
  207.                     key = key[0]
  208.         return UserDict.__setitem__(self, key, value)
  209.  
  210.     def get(self, key, default=None):
  211.         if self.has_key(key):
  212.             return self[key]
  213.         else:
  214.             return default
  215.  
  216.     def setdefault(self, key, value):
  217.         if not self.has_key(key):
  218.             self[key] = value
  219.         return self[key]
  220.         
  221.     def has_key(self, key):
  222.         try:
  223.             return hasattr(self, key) or UserDict.has_key(self, key)
  224.         except AttributeError:
  225.             return False
  226.         
  227.     def __getattr__(self, key):
  228.         try:
  229.             return self.__dict__[key]
  230.         except KeyError:
  231.             pass
  232.         try:
  233.             assert not key.startswith('_')
  234.             return self.__getitem__(key)
  235.         except:
  236.             raise AttributeError, "object has no attribute '%s'" % key
  237.  
  238.     def __setattr__(self, key, value):
  239.         if key.startswith('_') or key == 'data':
  240.             self.__dict__[key] = value
  241.         else:
  242.             return self.__setitem__(key, value)
  243.  
  244.     def __contains__(self, key):
  245.         return self.has_key(key)
  246.  
  247. def zopeCompatibilityHack():
  248.     global FeedParserDict
  249.     del FeedParserDict
  250.     def FeedParserDict(aDict=None):
  251.         rc = {}
  252.         if aDict:
  253.             rc.update(aDict)
  254.         return rc
  255.  
  256. _ebcdic_to_ascii_map = None
  257. def _ebcdic_to_ascii(s):
  258.     global _ebcdic_to_ascii_map
  259.     if not _ebcdic_to_ascii_map:
  260.         emap = (
  261.             0,1,2,3,156,9,134,127,151,141,142,11,12,13,14,15,
  262.             16,17,18,19,157,133,8,135,24,25,146,143,28,29,30,31,
  263.             128,129,130,131,132,10,23,27,136,137,138,139,140,5,6,7,
  264.             144,145,22,147,148,149,150,4,152,153,154,155,20,21,158,26,
  265.             32,160,161,162,163,164,165,166,167,168,91,46,60,40,43,33,
  266.             38,169,170,171,172,173,174,175,176,177,93,36,42,41,59,94,
  267.             45,47,178,179,180,181,182,183,184,185,124,44,37,95,62,63,
  268.             186,187,188,189,190,191,192,193,194,96,58,35,64,39,61,34,
  269.             195,97,98,99,100,101,102,103,104,105,196,197,198,199,200,201,
  270.             202,106,107,108,109,110,111,112,113,114,203,204,205,206,207,208,
  271.             209,126,115,116,117,118,119,120,121,122,210,211,212,213,214,215,
  272.             216,217,218,219,220,221,222,223,224,225,226,227,228,229,230,231,
  273.             123,65,66,67,68,69,70,71,72,73,232,233,234,235,236,237,
  274.             125,74,75,76,77,78,79,80,81,82,238,239,240,241,242,243,
  275.             92,159,83,84,85,86,87,88,89,90,244,245,246,247,248,249,
  276.             48,49,50,51,52,53,54,55,56,57,250,251,252,253,254,255
  277.             )
  278.         import string
  279.         _ebcdic_to_ascii_map = string.maketrans( \
  280.             ''.join(map(chr, range(256))), ''.join(map(chr, emap)))
  281.     return s.translate(_ebcdic_to_ascii_map)
  282.  
  283. _urifixer = re.compile('^([A-Za-z][A-Za-z0-9+-.]*://)(/*)(.*?)')
  284. def _urljoin(base, uri):
  285.     uri = _urifixer.sub(r'\1\3', uri)
  286.     return urlparse.urljoin(base, uri)
  287.  
  288. class _FeedParserMixin:
  289.     namespaces = {'': '',
  290.                   'http://backend.userland.com/rss': '',
  291.                   'http://blogs.law.harvard.edu/tech/rss': '',
  292.                   'http://purl.org/rss/1.0/': '',
  293.                   'http://my.netscape.com/rdf/simple/0.9/': '',
  294.                   'http://example.com/newformat#': '',
  295.                   'http://example.com/necho': '',
  296.                   'http://purl.org/echo/': '',
  297.                   'uri/of/echo/namespace#': '',
  298.                   'http://purl.org/pie/': '',
  299.                   'http://purl.org/atom/ns#': '',
  300.                   'http://www.w3.org/2005/Atom': '',
  301.                   'http://purl.org/rss/1.0/modules/rss091#': '',
  302.                   
  303.                   'http://webns.net/mvcb/':                               'admin',
  304.                   'http://purl.org/rss/1.0/modules/aggregation/':         'ag',
  305.                   'http://purl.org/rss/1.0/modules/annotate/':            'annotate',
  306.                   'http://media.tangent.org/rss/1.0/':                    'audio',
  307.                   'http://backend.userland.com/blogChannelModule':        'blogChannel',
  308.                   'http://web.resource.org/cc/':                          'cc',
  309.                   'http://backend.userland.com/creativeCommonsRssModule': 'creativeCommons',
  310.                   'http://purl.org/rss/1.0/modules/company':              'co',
  311.                   'http://purl.org/rss/1.0/modules/content/':             'content',
  312.                   'http://my.theinfo.org/changed/1.0/rss/':               'cp',
  313.                   'http://purl.org/dc/elements/1.1/':                     'dc',
  314.                   'http://purl.org/dc/terms/':                            'dcterms',
  315.                   'http://purl.org/rss/1.0/modules/email/':               'email',
  316.                   'http://purl.org/rss/1.0/modules/event/':               'ev',
  317.                   'http://rssnamespace.org/feedburner/ext/1.0':           'feedburner',
  318.                   'http://freshmeat.net/rss/fm/':                         'fm',
  319.                   'http://xmlns.com/foaf/0.1/':                           'foaf',
  320.                   'http://www.w3.org/2003/01/geo/wgs84_pos#':             'geo',
  321.                   'http://postneo.com/icbm/':                             'icbm',
  322.                   'http://purl.org/rss/1.0/modules/image/':               'image',
  323.                   'http://www.itunes.com/DTDs/PodCast-1.0.dtd':           'itunes',
  324.                   'http://example.com/DTDs/PodCast-1.0.dtd':              'itunes',
  325.                   'http://purl.org/rss/1.0/modules/link/':                'l',
  326.                   'http://search.yahoo.com/mrss':                         'media',
  327.                   'http://madskills.com/public/xml/rss/module/pingback/': 'pingback',
  328.                   'http://prismstandard.org/namespaces/1.2/basic/':       'prism',
  329.                   'http://www.w3.org/1999/02/22-rdf-syntax-ns#':          'rdf',
  330.                   'http://www.w3.org/2000/01/rdf-schema#':                'rdfs',
  331.                   'http://purl.org/rss/1.0/modules/reference/':           'ref',
  332.                   'http://purl.org/rss/1.0/modules/richequiv/':           'reqv',
  333.                   'http://purl.org/rss/1.0/modules/search/':              'search',
  334.                   'http://purl.org/rss/1.0/modules/slash/':               'slash',
  335.                   'http://schemas.xmlsoap.org/soap/envelope/':            'soap',
  336.                   'http://purl.org/rss/1.0/modules/servicestatus/':       'ss',
  337.                   'http://hacks.benhammersley.com/rss/streaming/':        'str',
  338.                   'http://purl.org/rss/1.0/modules/subscription/':        'sub',
  339.                   'http://purl.org/rss/1.0/modules/syndication/':         'sy',
  340.                   'http://purl.org/rss/1.0/modules/taxonomy/':            'taxo',
  341.                   'http://purl.org/rss/1.0/modules/threading/':           'thr',
  342.                   'http://purl.org/rss/1.0/modules/textinput/':           'ti',
  343.                   'http://madskills.com/public/xml/rss/module/trackback/':'trackback',
  344.                   'http://wellformedweb.org/commentAPI/':                 'wfw',
  345.                   'http://purl.org/rss/1.0/modules/wiki/':                'wiki',
  346.                   'http://www.w3.org/1999/xhtml':                         'xhtml',
  347.                   'http://www.w3.org/XML/1998/namespace':                 'xml',
  348.                   'http://schemas.pocketsoap.com/rss/myDescModule/':      'szf'
  349. }
  350.     _matchnamespaces = {}
  351.  
  352.     can_be_relative_uri = ['link', 'id', 'wfw_comment', 'wfw_commentrss', 'docs', 'url', 'href', 'comments', 'license', 'icon', 'logo']
  353.     can_contain_relative_uris = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  354.     can_contain_dangerous_markup = ['content', 'title', 'summary', 'info', 'tagline', 'subtitle', 'copyright', 'rights', 'description']
  355.     html_types = ['text/html', 'application/xhtml+xml']
  356.     
  357.     def __init__(self, baseuri=None, baselang=None, encoding='utf-8'):
  358.         if _debug: sys.stderr.write('initializing FeedParser\n')
  359.         if not self._matchnamespaces:
  360.             for k, v in self.namespaces.items():
  361.                 self._matchnamespaces[k.lower()] = v
  362.         self.feeddata = FeedParserDict() # feed-level data
  363.         self.encoding = encoding # character encoding
  364.         self.entries = [] # list of entry-level data
  365.         self.version = '' # feed type/version, see SUPPORTED_VERSIONS
  366.         self.namespacesInUse = {} # dictionary of namespaces defined by the feed
  367.  
  368.         # the following are used internally to track state;
  369.         # this is really out of control and should be refactored
  370.         self.infeed = 0
  371.         self.inentry = 0
  372.         self.incontent = 0
  373.         self.intextinput = 0
  374.         self.inimage = 0
  375.         self.inauthor = 0
  376.         self.incontributor = 0
  377.         self.inpublisher = 0
  378.         self.insource = 0
  379.         self.sourcedata = FeedParserDict()
  380.         self.contentparams = FeedParserDict()
  381.         self._summaryKey = None
  382.         self.namespacemap = {}
  383.         self.elementstack = []
  384.         self.basestack = []
  385.         self.langstack = []
  386.         self.baseuri = baseuri or ''
  387.         self.lang = baselang or None
  388.         if baselang:
  389.             self.feeddata['language'] = baselang
  390.  
  391.     def unknown_starttag(self, tag, attrs):
  392.         if _debug: sys.stderr.write('start %s with %s\n' % (tag, attrs))
  393.         # normalize attrs
  394.         attrs = [(k.lower(), v) for k, v in attrs]
  395.         attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  396.         
  397.         # track xml:base and xml:lang
  398.         attrsD = dict(attrs)
  399.         baseuri = attrsD.get('xml:base', attrsD.get('base')) or self.baseuri
  400.         self.baseuri = _urljoin(self.baseuri, baseuri)
  401.         lang = attrsD.get('xml:lang', attrsD.get('lang'))
  402.         if lang == '':
  403.             # xml:lang could be explicitly set to '', we need to capture that
  404.             lang = None
  405.         elif lang is None:
  406.             # if no xml:lang is specified, use parent lang
  407.             lang = self.lang
  408.         if lang:
  409.             if tag in ('feed', 'rss', 'rdf:RDF'):
  410.                 self.feeddata['language'] = lang
  411.         self.lang = lang
  412.         self.basestack.append(self.baseuri)
  413.         self.langstack.append(lang)
  414.         
  415.         # track namespaces
  416.         for prefix, uri in attrs:
  417.             if prefix.startswith('xmlns:'):
  418.                 self.trackNamespace(prefix[6:], uri)
  419.             elif prefix == 'xmlns':
  420.                 self.trackNamespace(None, uri)
  421.  
  422.         # track inline content
  423.         if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  424.             # element declared itself as escaped markup, but it isn't really
  425.             self.contentparams['type'] = 'application/xhtml+xml'
  426.         if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  427.             # Note: probably shouldn't simply recreate localname here, but
  428.             # our namespace handling isn't actually 100% correct in cases where
  429.             # the feed redefines the default namespace (which is actually
  430.             # the usual case for inline content, thanks Sam), so here we
  431.             # cheat and just reconstruct the element based on localname
  432.             # because that compensates for the bugs in our namespace handling.
  433.             # This will horribly munge inline content with non-empty qnames,
  434.             # but nobody actually does that, so I'm not fixing it.
  435.             tag = tag.split(':')[-1]
  436.             return self.handle_data('<%s%s>' % (tag, ''.join([' %s="%s"' % t for t in attrs])), escape=0)
  437.  
  438.         # match namespaces
  439.         if tag.find(':') <> -1:
  440.             prefix, suffix = tag.split(':', 1)
  441.         else:
  442.             prefix, suffix = '', tag
  443.         prefix = self.namespacemap.get(prefix, prefix)
  444.         if prefix:
  445.             prefix = prefix + '_'
  446.  
  447.         # special hack for better tracking of empty textinput/image elements in illformed feeds
  448.         if (not prefix) and tag not in ('title', 'link', 'description', 'name'):
  449.             self.intextinput = 0
  450.         if (not prefix) and tag not in ('title', 'link', 'description', 'url', 'href', 'width', 'height'):
  451.             self.inimage = 0
  452.         
  453.         # call special handler (if defined) or default handler
  454.         methodname = '_start_' + prefix + suffix
  455.         try:
  456.             method = getattr(self, methodname)
  457.             return method(attrsD)
  458.         except AttributeError:
  459.             return self.push(prefix + suffix, 1)
  460.  
  461.     def unknown_endtag(self, tag):
  462.         if _debug: sys.stderr.write('end %s\n' % tag)
  463.         # match namespaces
  464.         if tag.find(':') <> -1:
  465.             prefix, suffix = tag.split(':', 1)
  466.         else:
  467.             prefix, suffix = '', tag
  468.         prefix = self.namespacemap.get(prefix, prefix)
  469.         if prefix:
  470.             prefix = prefix + '_'
  471.  
  472.         # call special handler (if defined) or default handler
  473.         methodname = '_end_' + prefix + suffix
  474.         try:
  475.             method = getattr(self, methodname)
  476.             method()
  477.         except AttributeError:
  478.             self.pop(prefix + suffix)
  479.  
  480.         # track inline content
  481.         if self.incontent and self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  482.             # element declared itself as escaped markup, but it isn't really
  483.             self.contentparams['type'] = 'application/xhtml+xml'
  484.         if self.incontent and self.contentparams.get('type') == 'application/xhtml+xml':
  485.             tag = tag.split(':')[-1]
  486.             self.handle_data('</%s>' % tag, escape=0)
  487.  
  488.         # track xml:base and xml:lang going out of scope
  489.         if self.basestack:
  490.             self.basestack.pop()
  491.             if self.basestack and self.basestack[-1]:
  492.                 self.baseuri = self.basestack[-1]
  493.         if self.langstack:
  494.             self.langstack.pop()
  495.             if self.langstack: # and (self.langstack[-1] is not None):
  496.                 self.lang = self.langstack[-1]
  497.  
  498.     def handle_charref(self, ref):
  499.         # called for each character reference, e.g. for ' ', ref will be '160'
  500.         if not self.elementstack: return
  501.         ref = ref.lower()
  502.         if ref in ('34', '38', '39', '60', '62', 'x22', 'x26', 'x27', 'x3c', 'x3e'):
  503.             text = '&#%s;' % ref
  504.         else:
  505.             if ref[0] == 'x':
  506.                 c = int(ref[1:], 16)
  507.             else:
  508.                 c = int(ref)
  509.             text = unichr(c).encode('utf-8')
  510.         self.elementstack[-1][2].append(text)
  511.  
  512.     def handle_entityref(self, ref):
  513.         # called for each entity reference, e.g. for '©', ref will be 'copy'
  514.         if not self.elementstack: return
  515.         if _debug: sys.stderr.write('entering handle_entityref with %s\n' % ref)
  516.         if ref in ('lt', 'gt', 'quot', 'amp', 'apos'):
  517.             text = '&%s;' % ref
  518.         else:
  519.             # entity resolution graciously donated by Aaron Swartz
  520.             def name2cp(k):
  521.                 import htmlentitydefs
  522.                 if hasattr(htmlentitydefs, 'name2codepoint'): # requires Python 2.3
  523.                     return htmlentitydefs.name2codepoint[k]
  524.                 k = htmlentitydefs.entitydefs[k]
  525.                 if k.startswith('&#') and k.endswith(';'):
  526.                     return int(k[2:-1]) # not in latin-1
  527.                 return ord(k)
  528.             try: name2cp(ref)
  529.             except KeyError: text = '&%s;' % ref
  530.             else: text = unichr(name2cp(ref)).encode('utf-8')
  531.         self.elementstack[-1][2].append(text)
  532.  
  533.     def handle_data(self, text, escape=1):
  534.         # called for each block of plain text, i.e. outside of any tag and
  535.         # not containing any character or entity references
  536.         if not self.elementstack: return
  537.         if escape and self.contentparams.get('type') == 'application/xhtml+xml':
  538.             text = _xmlescape(text)
  539.         self.elementstack[-1][2].append(text)
  540.  
  541.     def handle_comment(self, text):
  542.         # called for each comment, e.g. <!-- insert message here -->
  543.         pass
  544.  
  545.     def handle_pi(self, text):
  546.         # called for each processing instruction, e.g. <?instruction>
  547.         pass
  548.  
  549.     def handle_decl(self, text):
  550.         pass
  551.  
  552.     def parse_declaration(self, i):
  553.         # override internal declaration handler to handle CDATA blocks
  554.         if _debug: sys.stderr.write('entering parse_declaration\n')
  555.         if self.rawdata[i:i+9] == '<![CDATA[':
  556.             k = self.rawdata.find(']]>', i)
  557.             if k == -1: k = len(self.rawdata)
  558.             self.handle_data(_xmlescape(self.rawdata[i+9:k]), 0)
  559.             return k+3
  560.         else:
  561.             k = self.rawdata.find('>', i)
  562.             return k+1
  563.  
  564.     def mapContentType(self, contentType):
  565.         contentType = contentType.lower()
  566.         if contentType == 'text' or contentType == 'plain':
  567.             contentType = 'text/plain'
  568.         elif contentType == 'html':
  569.             contentType = 'text/html'
  570.         elif contentType == 'xhtml':
  571.             contentType = 'application/xhtml+xml'
  572.         return contentType
  573.     
  574.     def trackNamespace(self, prefix, uri):
  575.         loweruri = uri.lower()
  576.         if (prefix, loweruri) == (None, 'http://my.netscape.com/rdf/simple/0.9/') and not self.version:
  577.             self.version = 'rss090'
  578.         if loweruri == 'http://purl.org/rss/1.0/' and not self.version:
  579.             self.version = 'rss10'
  580.         if loweruri == 'http://www.w3.org/2005/atom' and not self.version:
  581.             self.version = 'atom10'
  582.         if loweruri.find('backend.userland.com/rss') <> -1:
  583.             # match any backend.userland.com namespace
  584.             uri = 'http://backend.userland.com/rss'
  585.             loweruri = uri
  586.         if self._matchnamespaces.has_key(loweruri):
  587.             self.namespacemap[prefix] = self._matchnamespaces[loweruri]
  588.             self.namespacesInUse[self._matchnamespaces[loweruri]] = uri
  589.         else:
  590.             self.namespacesInUse[prefix or ''] = uri
  591.  
  592.     def resolveURI(self, uri):
  593.         return _urljoin(self.baseuri or '', uri)
  594.     
  595.     def decodeEntities(self, element, data):
  596.         return data
  597.  
  598.     def push(self, element, expectingText):
  599.         self.elementstack.append([element, expectingText, []])
  600.  
  601.     def pop(self, element, stripWhitespace=1):
  602.         if not self.elementstack: return
  603.         if self.elementstack[-1][0] != element: return
  604.         
  605.         element, expectingText, pieces = self.elementstack.pop()
  606.         output = ''.join(pieces)
  607.         if stripWhitespace:
  608.             output = output.strip()
  609.         if not expectingText: return output
  610.  
  611.         # decode base64 content
  612.         if base64 and self.contentparams.get('base64', 0):
  613.             try:
  614.                 output = base64.decodestring(output)
  615.             except binascii.Error:
  616.                 pass
  617.             except binascii.Incomplete:
  618.                 pass
  619.                 
  620.         # resolve relative URIs
  621.         if (element in self.can_be_relative_uri) and output:
  622.             output = self.resolveURI(output)
  623.         
  624.         # decode entities within embedded markup
  625.         if not self.contentparams.get('base64', 0):
  626.             output = self.decodeEntities(element, output)
  627.  
  628.         # remove temporary cruft from contentparams
  629.         try:
  630.             del self.contentparams['mode']
  631.         except KeyError:
  632.             pass
  633.         try:
  634.             del self.contentparams['base64']
  635.         except KeyError:
  636.             pass
  637.  
  638.         # resolve relative URIs within embedded markup
  639.         if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  640.             if element in self.can_contain_relative_uris:
  641.                 output = _resolveRelativeURIs(output, self.baseuri, self.encoding)
  642.         
  643.         # sanitize embedded markup
  644.         if self.mapContentType(self.contentparams.get('type', 'text/html')) in self.html_types:
  645.             if element in self.can_contain_dangerous_markup:
  646.                 output = _sanitizeHTML(output, self.encoding)
  647.  
  648.         if self.encoding and type(output) != type(u''):
  649.             try:
  650.                 output = unicode(output, self.encoding)
  651.             except:
  652.                 pass
  653.  
  654.         # categories/tags/keywords/whatever are handled in _end_category
  655.         if element == 'category':
  656.             return output
  657.         
  658.         # store output in appropriate place(s)
  659.         if self.inentry and not self.insource:
  660.             if element == 'content':
  661.                 self.entries[-1].setdefault(element, [])
  662.                 contentparams = copy.deepcopy(self.contentparams)
  663.                 contentparams['value'] = output
  664.                 self.entries[-1][element].append(contentparams)
  665.             elif element == 'link':
  666.                 self.entries[-1][element] = output
  667.                 if output:
  668.                     self.entries[-1]['links'][-1]['href'] = output
  669.             else:
  670.                 if element == 'description':
  671.                     element = 'summary'
  672.                 self.entries[-1][element] = output
  673.                 if self.incontent:
  674.                     contentparams = copy.deepcopy(self.contentparams)
  675.                     contentparams['value'] = output
  676.                     self.entries[-1][element + '_detail'] = contentparams
  677.         elif (self.infeed or self.insource) and (not self.intextinput) and (not self.inimage):
  678.             context = self._getContext()
  679.             if element == 'description':
  680.                 element = 'subtitle'
  681.             context[element] = output
  682.             if element == 'link':
  683.                 context['links'][-1]['href'] = output
  684.             elif self.incontent:
  685.                 contentparams = copy.deepcopy(self.contentparams)
  686.                 contentparams['value'] = output
  687.                 context[element + '_detail'] = contentparams
  688.         return output
  689.  
  690.     def pushContent(self, tag, attrsD, defaultContentType, expectingText):
  691.         self.incontent += 1
  692.         self.contentparams = FeedParserDict({
  693.             'type': self.mapContentType(attrsD.get('type', defaultContentType)),
  694.             'language': self.lang,
  695.             'base': self.baseuri})
  696.         self.contentparams['base64'] = self._isBase64(attrsD, self.contentparams)
  697.         self.push(tag, expectingText)
  698.  
  699.     def popContent(self, tag):
  700.         value = self.pop(tag)
  701.         self.incontent -= 1
  702.         self.contentparams.clear()
  703.         return value
  704.         
  705.     def _mapToStandardPrefix(self, name):
  706.         colonpos = name.find(':')
  707.         if colonpos <> -1:
  708.             prefix = name[:colonpos]
  709.             suffix = name[colonpos+1:]
  710.             prefix = self.namespacemap.get(prefix, prefix)
  711.             name = prefix + ':' + suffix
  712.         return name
  713.         
  714.     def _getAttribute(self, attrsD, name):
  715.         return attrsD.get(self._mapToStandardPrefix(name))
  716.  
  717.     def _isBase64(self, attrsD, contentparams):
  718.         if attrsD.get('mode', '') == 'base64':
  719.             return 1
  720.         if self.contentparams['type'].startswith('text/'):
  721.             return 0
  722.         if self.contentparams['type'].endswith('+xml'):
  723.             return 0
  724.         if self.contentparams['type'].endswith('/xml'):
  725.             return 0
  726.         return 1
  727.  
  728.     def _itsAnHrefDamnIt(self, attrsD):
  729.         href = attrsD.get('url', attrsD.get('uri', attrsD.get('href', None)))
  730.         if href:
  731.             try:
  732.                 del attrsD['url']
  733.             except KeyError:
  734.                 pass
  735.             try:
  736.                 del attrsD['uri']
  737.             except KeyError:
  738.                 pass
  739.             attrsD['href'] = href
  740.         return attrsD
  741.     
  742.     def _save(self, key, value):
  743.         context = self._getContext()
  744.         context.setdefault(key, value)
  745.  
  746.     def _start_rss(self, attrsD):
  747.         versionmap = {'0.91': 'rss091u',
  748.                       '0.92': 'rss092',
  749.                       '0.93': 'rss093',
  750.                       '0.94': 'rss094'}
  751.         if not self.version:
  752.             attr_version = attrsD.get('version', '')
  753.             version = versionmap.get(attr_version)
  754.             if version:
  755.                 self.version = version
  756.             elif attr_version.startswith('2.'):
  757.                 self.version = 'rss20'
  758.             else:
  759.                 self.version = 'rss'
  760.     
  761.     def _start_dlhottitles(self, attrsD):
  762.         self.version = 'hotrss'
  763.  
  764.     def _start_channel(self, attrsD):
  765.         self.infeed = 1
  766.         self._cdf_common(attrsD)
  767.     _start_feedinfo = _start_channel
  768.  
  769.     def _cdf_common(self, attrsD):
  770.         if attrsD.has_key('lastmod'):
  771.             self._start_modified({})
  772.             self.elementstack[-1][-1] = attrsD['lastmod']
  773.             self._end_modified()
  774.         if attrsD.has_key('href'):
  775.             self._start_link({})
  776.             self.elementstack[-1][-1] = attrsD['href']
  777.             self._end_link()
  778.     
  779.     def _start_feed(self, attrsD):
  780.         self.infeed = 1
  781.         versionmap = {'0.1': 'atom01',
  782.                       '0.2': 'atom02',
  783.                       '0.3': 'atom03'}
  784.         if not self.version:
  785.             attr_version = attrsD.get('version')
  786.             version = versionmap.get(attr_version)
  787.             if version:
  788.                 self.version = version
  789.             else:
  790.                 self.version = 'atom'
  791.  
  792.     def _end_channel(self):
  793.         self.infeed = 0
  794.     _end_feed = _end_channel
  795.     
  796.     def _start_image(self, attrsD):
  797.         self.inimage = 1
  798.         self.push('image', 0)
  799.         context = self._getContext()
  800.         context.setdefault('image', FeedParserDict())
  801.             
  802.     def _end_image(self):
  803.         self.pop('image')
  804.         self.inimage = 0
  805.  
  806.     def _start_textinput(self, attrsD):
  807.         self.intextinput = 1
  808.         self.push('textinput', 0)
  809.         context = self._getContext()
  810.         context.setdefault('textinput', FeedParserDict())
  811.     _start_textInput = _start_textinput
  812.     
  813.     def _end_textinput(self):
  814.         self.pop('textinput')
  815.         self.intextinput = 0
  816.     _end_textInput = _end_textinput
  817.  
  818.     def _start_author(self, attrsD):
  819.         self.inauthor = 1
  820.         self.push('author', 1)
  821.     _start_managingeditor = _start_author
  822.     _start_dc_author = _start_author
  823.     _start_dc_creator = _start_author
  824.     _start_itunes_author = _start_author
  825.  
  826.     def _end_author(self):
  827.         self.pop('author')
  828.         self.inauthor = 0
  829.         self._sync_author_detail()
  830.     _end_managingeditor = _end_author
  831.     _end_dc_author = _end_author
  832.     _end_dc_creator = _end_author
  833.     _end_itunes_author = _end_author
  834.  
  835.     def _start_itunes_owner(self, attrsD):
  836.         self.inpublisher = 1
  837.         self.push('publisher', 0)
  838.  
  839.     def _end_itunes_owner(self):
  840.         self.pop('publisher')
  841.         self.inpublisher = 0
  842.         self._sync_author_detail('publisher')
  843.  
  844.     def _start_contributor(self, attrsD):
  845.         self.incontributor = 1
  846.         context = self._getContext()
  847.         context.setdefault('contributors', [])
  848.         context['contributors'].append(FeedParserDict())
  849.         self.push('contributor', 0)
  850.  
  851.     def _end_contributor(self):
  852.         self.pop('contributor')
  853.         self.incontributor = 0
  854.  
  855.     def _start_dc_contributor(self, attrsD):
  856.         self.incontributor = 1
  857.         context = self._getContext()
  858.         context.setdefault('contributors', [])
  859.         context['contributors'].append(FeedParserDict())
  860.         self.push('name', 0)
  861.  
  862.     def _end_dc_contributor(self):
  863.         self._end_name()
  864.         self.incontributor = 0
  865.  
  866.     def _start_name(self, attrsD):
  867.         self.push('name', 0)
  868.     _start_itunes_name = _start_name
  869.  
  870.     def _end_name(self):
  871.         value = self.pop('name')
  872.         if self.inpublisher:
  873.             self._save_author('name', value, 'publisher')
  874.         elif self.inauthor:
  875.             self._save_author('name', value)
  876.         elif self.incontributor:
  877.             self._save_contributor('name', value)
  878.         elif self.intextinput:
  879.             context = self._getContext()
  880.             context['textinput']['name'] = value
  881.     _end_itunes_name = _end_name
  882.  
  883.     def _start_width(self, attrsD):
  884.         self.push('width', 0)
  885.  
  886.     def _end_width(self):
  887.         value = self.pop('width')
  888.         try:
  889.             value = int(value)
  890.         except:
  891.             value = 0
  892.         if self.inimage:
  893.             context = self._getContext()
  894.             context['image']['width'] = value
  895.  
  896.     def _start_height(self, attrsD):
  897.         self.push('height', 0)
  898.  
  899.     def _end_height(self):
  900.         value = self.pop('height')
  901.         try:
  902.             value = int(value)
  903.         except:
  904.             value = 0
  905.         if self.inimage:
  906.             context = self._getContext()
  907.             context['image']['height'] = value
  908.  
  909.     def _start_url(self, attrsD):
  910.         self.push('href', 1)
  911.     _start_homepage = _start_url
  912.     _start_uri = _start_url
  913.  
  914.     def _end_url(self):
  915.         value = self.pop('href')
  916.         if self.inauthor:
  917.             self._save_author('href', value)
  918.         elif self.incontributor:
  919.             self._save_contributor('href', value)
  920.         elif self.inimage:
  921.             context = self._getContext()
  922.             context['image']['href'] = value
  923.         elif self.intextinput:
  924.             context = self._getContext()
  925.             context['textinput']['link'] = value
  926.     _end_homepage = _end_url
  927.     _end_uri = _end_url
  928.  
  929.     def _start_email(self, attrsD):
  930.         self.push('email', 0)
  931.     _start_itunes_email = _start_email
  932.  
  933.     def _end_email(self):
  934.         value = self.pop('email')
  935.         if self.inpublisher:
  936.             self._save_author('email', value, 'publisher')
  937.         elif self.inauthor:
  938.             self._save_author('email', value)
  939.         elif self.incontributor:
  940.             self._save_contributor('email', value)
  941.     _end_itunes_email = _end_email
  942.  
  943.     def _getContext(self):
  944.         if self.insource:
  945.             context = self.sourcedata
  946.         elif self.inentry:
  947.             context = self.entries[-1]
  948.         else:
  949.             context = self.feeddata
  950.         return context
  951.  
  952.     def _save_author(self, key, value, prefix='author'):
  953.         context = self._getContext()
  954.         context.setdefault(prefix + '_detail', FeedParserDict())
  955.         context[prefix + '_detail'][key] = value
  956.         self._sync_author_detail()
  957.  
  958.     def _save_contributor(self, key, value):
  959.         context = self._getContext()
  960.         context.setdefault('contributors', [FeedParserDict()])
  961.         context['contributors'][-1][key] = value
  962.  
  963.     def _sync_author_detail(self, key='author'):
  964.         context = self._getContext()
  965.         detail = context.get('%s_detail' % key)
  966.         if detail:
  967.             name = detail.get('name')
  968.             email = detail.get('email')
  969.             if name and email:
  970.                 context[key] = '%s (%s)' % (name, email)
  971.             elif name:
  972.                 context[key] = name
  973.             elif email:
  974.                 context[key] = email
  975.         else:
  976.             author = context.get(key)
  977.             if not author: return
  978.             emailmatch = re.search(r'''(([a-zA-Z0-9\_\-\.\+]+)@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.)|(([a-zA-Z0-9\-]+\.)+))([a-zA-Z]{2,4}|[0-9]{1,3})(\]?))''', author)
  979.             if not emailmatch: return
  980.             email = emailmatch.group(0)
  981.             # probably a better way to do the following, but it passes all the tests
  982.             author = author.replace(email, '')
  983.             author = author.replace('()', '')
  984.             author = author.strip()
  985.             if author and (author[0] == '('):
  986.                 author = author[1:]
  987.             if author and (author[-1] == ')'):
  988.                 author = author[:-1]
  989.             author = author.strip()
  990.             context.setdefault('%s_detail' % key, FeedParserDict())
  991.             context['%s_detail' % key]['name'] = author
  992.             context['%s_detail' % key]['email'] = email
  993.  
  994.     def _start_subtitle(self, attrsD):
  995.         self.pushContent('subtitle', attrsD, 'text/plain', 1)
  996.     _start_tagline = _start_subtitle
  997.     _start_itunes_subtitle = _start_subtitle
  998.  
  999.     def _end_subtitle(self):
  1000.         self.popContent('subtitle')
  1001.     _end_tagline = _end_subtitle
  1002.     _end_itunes_subtitle = _end_subtitle
  1003.             
  1004.     def _start_rights(self, attrsD):
  1005.         self.pushContent('rights', attrsD, 'text/plain', 1)
  1006.     _start_dc_rights = _start_rights
  1007.     _start_copyright = _start_rights
  1008.  
  1009.     def _end_rights(self):
  1010.         self.popContent('rights')
  1011.     _end_dc_rights = _end_rights
  1012.     _end_copyright = _end_rights
  1013.  
  1014.     def _start_item(self, attrsD):
  1015.         self.entries.append(FeedParserDict())
  1016.         self.push('item', 0)
  1017.         self.inentry = 1
  1018.         self.guidislink = 0
  1019.         id = self._getAttribute(attrsD, 'rdf:about')
  1020.         if id:
  1021.             context = self._getContext()
  1022.             context['id'] = id
  1023.         self._cdf_common(attrsD)
  1024.     _start_entry = _start_item
  1025.     _start_product = _start_item
  1026.  
  1027.     def _end_item(self):
  1028.         self.pop('item')
  1029.         self.inentry = 0
  1030.     _end_entry = _end_item
  1031.  
  1032.     def _start_dc_language(self, attrsD):
  1033.         self.push('language', 1)
  1034.     _start_language = _start_dc_language
  1035.  
  1036.     def _end_dc_language(self):
  1037.         self.lang = self.pop('language')
  1038.     _end_language = _end_dc_language
  1039.  
  1040.     def _start_dc_publisher(self, attrsD):
  1041.         self.push('publisher', 1)
  1042.     _start_webmaster = _start_dc_publisher
  1043.  
  1044.     def _end_dc_publisher(self):
  1045.         self.pop('publisher')
  1046.         self._sync_author_detail('publisher')
  1047.     _end_webmaster = _end_dc_publisher
  1048.  
  1049.     def _start_published(self, attrsD):
  1050.         self.push('published', 1)
  1051.     _start_dcterms_issued = _start_published
  1052.     _start_issued = _start_published
  1053.  
  1054.     def _end_published(self):
  1055.         value = self.pop('published')
  1056.         self._save('published_parsed', _parse_date(value))
  1057.     _end_dcterms_issued = _end_published
  1058.     _end_issued = _end_published
  1059.  
  1060.     def _start_updated(self, attrsD):
  1061.         self.push('updated', 1)
  1062.     _start_modified = _start_updated
  1063.     _start_dcterms_modified = _start_updated
  1064.     _start_pubdate = _start_updated
  1065.     _start_dc_date = _start_updated
  1066.  
  1067.     def _end_updated(self):
  1068.         value = self.pop('updated')
  1069.         parsed_value = _parse_date(value)
  1070.         self._save('updated_parsed', parsed_value)
  1071.     _end_modified = _end_updated
  1072.     _end_dcterms_modified = _end_updated
  1073.     _end_pubdate = _end_updated
  1074.     _end_dc_date = _end_updated
  1075.  
  1076.     def _start_created(self, attrsD):
  1077.         self.push('created', 1)
  1078.     _start_dcterms_created = _start_created
  1079.  
  1080.     def _end_created(self):
  1081.         value = self.pop('created')
  1082.         self._save('created_parsed', _parse_date(value))
  1083.     _end_dcterms_created = _end_created
  1084.  
  1085.     def _start_expirationdate(self, attrsD):
  1086.         self.push('expired', 1)
  1087.  
  1088.     def _end_expirationdate(self):
  1089.         self._save('expired_parsed', _parse_date(self.pop('expired')))
  1090.  
  1091.     def _start_cc_license(self, attrsD):
  1092.         self.push('license', 1)
  1093.         value = self._getAttribute(attrsD, 'rdf:resource')
  1094.         if value:
  1095.             self.elementstack[-1][2].append(value)
  1096.         self.pop('license')
  1097.         
  1098.     def _start_creativecommons_license(self, attrsD):
  1099.         self.push('license', 1)
  1100.  
  1101.     def _end_creativecommons_license(self):
  1102.         self.pop('license')
  1103.  
  1104.     def _addTag(self, term, scheme, label):
  1105.         context = self._getContext()
  1106.         tags = context.setdefault('tags', [])
  1107.         if (not term) and (not scheme) and (not label): return
  1108.         value = FeedParserDict({'term': term, 'scheme': scheme, 'label': label})
  1109.         if value not in tags:
  1110.             tags.append(FeedParserDict({'term': term, 'scheme': scheme, 'label': label}))
  1111.  
  1112.     def _start_category(self, attrsD):
  1113.         if _debug: sys.stderr.write('entering _start_category with %s\n' % repr(attrsD))
  1114.         term = attrsD.get('term')
  1115.         scheme = attrsD.get('scheme', attrsD.get('domain'))
  1116.         label = attrsD.get('label')
  1117.         self._addTag(term, scheme, label)
  1118.         self.push('category', 1)
  1119.     _start_dc_subject = _start_category
  1120.     _start_keywords = _start_category
  1121.         
  1122.     def _end_itunes_keywords(self):
  1123.         for term in self.pop('itunes_keywords').split():
  1124.             self._addTag(term, 'http://www.itunes.com/', None)
  1125.         
  1126.     def _start_itunes_category(self, attrsD):
  1127.         self._addTag(attrsD.get('text'), 'http://www.itunes.com/', None)
  1128.         self.push('category', 1)
  1129.         
  1130.     def _end_category(self):
  1131.         value = self.pop('category')
  1132.         if not value: return
  1133.         context = self._getContext()
  1134.         tags = context['tags']
  1135.         if value and len(tags) and not tags[-1]['term']:
  1136.             tags[-1]['term'] = value
  1137.         else:
  1138.             self._addTag(value, None, None)
  1139.     _end_dc_subject = _end_category
  1140.     _end_keywords = _end_category
  1141.     _end_itunes_category = _end_category
  1142.  
  1143.     def _start_cloud(self, attrsD):
  1144.         self._getContext()['cloud'] = FeedParserDict(attrsD)
  1145.         
  1146.     def _start_link(self, attrsD):
  1147.         attrsD.setdefault('rel', 'alternate')
  1148.         attrsD.setdefault('type', 'text/html')
  1149.         attrsD = self._itsAnHrefDamnIt(attrsD)
  1150.         if attrsD.has_key('href'):
  1151.             attrsD['href'] = self.resolveURI(attrsD['href'])
  1152.         expectingText = self.infeed or self.inentry or self.insource
  1153.         context = self._getContext()
  1154.         context.setdefault('links', [])
  1155.         context['links'].append(FeedParserDict(attrsD))
  1156.         if attrsD['rel'] == 'enclosure':
  1157.             self._start_enclosure(attrsD)
  1158.         if attrsD.has_key('href'):
  1159.             expectingText = 0
  1160.             if (attrsD.get('rel') == 'alternate') and (self.mapContentType(attrsD.get('type')) in self.html_types):
  1161.                 context['link'] = attrsD['href']
  1162.         else:
  1163.             self.push('link', expectingText)
  1164.     _start_producturl = _start_link
  1165.  
  1166.     def _end_link(self):
  1167.         value = self.pop('link')
  1168.         context = self._getContext()
  1169.         if self.intextinput:
  1170.             context['textinput']['link'] = value
  1171.         if self.inimage:
  1172.             context['image']['link'] = value
  1173.     _end_producturl = _end_link
  1174.  
  1175.     def _start_guid(self, attrsD):
  1176.         self.guidislink = (attrsD.get('ispermalink', 'true') == 'true')
  1177.         self.push('id', 1)
  1178.  
  1179.     def _end_guid(self):
  1180.         value = self.pop('id')
  1181.         self._save('guidislink', self.guidislink and not self._getContext().has_key('link'))
  1182.         if self.guidislink:
  1183.             # guid acts as link, but only if 'ispermalink' is not present or is 'true',
  1184.             # and only if the item doesn't already have a link element
  1185.             self._save('link', value)
  1186.  
  1187.     def _start_title(self, attrsD):
  1188.         self.pushContent('title', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1189.  
  1190.     def _start_title_low_pri(self, attrsD):
  1191.         if not self._getContext().has_key('title'):
  1192.             self._start_title(attrsD)
  1193.  
  1194.     _start_dc_title = _start_title_low_pri
  1195.     _start_media_title = _start_title_low_pri
  1196.  
  1197.     def _end_title(self):
  1198.         value = self.popContent('title')
  1199.         context = self._getContext()
  1200.         if self.intextinput:
  1201.             context['textinput']['title'] = value
  1202.         elif self.inimage:
  1203.             context['image']['title'] = value
  1204.  
  1205.     def _end_title_low_pri(self):
  1206.         if not self._getContext().has_key('title'):
  1207.             self._end_title()
  1208.     _end_dc_title = _end_title_low_pri
  1209.     _end_media_title = _end_title_low_pri
  1210.  
  1211.     def _start_description(self, attrsD):
  1212.         context = self._getContext()
  1213.         if context.has_key('summary'):
  1214.             self._summaryKey = 'content'
  1215.             self._start_content(attrsD)
  1216.         else:
  1217.             self.pushContent('description', attrsD, 'text/html', self.infeed or self.inentry or self.insource)
  1218.  
  1219.     def _start_abstract(self, attrsD):
  1220.         self.pushContent('description', attrsD, 'text/plain', self.infeed or self.inentry or self.insource)
  1221.  
  1222.     def _end_description(self):
  1223.         if self._summaryKey == 'content':
  1224.             self._end_content()
  1225.         else:
  1226.             value = self.popContent('description')
  1227.             context = self._getContext()
  1228.             if self.intextinput:
  1229.                 context['textinput']['description'] = value
  1230.             elif self.inimage:
  1231.                 context['image']['description'] = value
  1232.         self._summaryKey = None
  1233.     _end_abstract = _end_description
  1234.  
  1235.     def _start_info(self, attrsD):
  1236.         self.pushContent('info', attrsD, 'text/plain', 1)
  1237.     _start_feedburner_browserfriendly = _start_info
  1238.  
  1239.     def _end_info(self):
  1240.         self.popContent('info')
  1241.     _end_feedburner_browserfriendly = _end_info
  1242.  
  1243.     def _start_generator(self, attrsD):
  1244.         if attrsD:
  1245.             attrsD = self._itsAnHrefDamnIt(attrsD)
  1246.             if attrsD.has_key('href'):
  1247.                 attrsD['href'] = self.resolveURI(attrsD['href'])
  1248.         self._getContext()['generator_detail'] = FeedParserDict(attrsD)
  1249.         self.push('generator', 1)
  1250.  
  1251.     def _end_generator(self):
  1252.         value = self.pop('generator')
  1253.         context = self._getContext()
  1254.         if context.has_key('generator_detail'):
  1255.             context['generator_detail']['name'] = value
  1256.             
  1257.     def _start_admin_generatoragent(self, attrsD):
  1258.         self.push('generator', 1)
  1259.         value = self._getAttribute(attrsD, 'rdf:resource')
  1260.         if value:
  1261.             self.elementstack[-1][2].append(value)
  1262.         self.pop('generator')
  1263.         self._getContext()['generator_detail'] = FeedParserDict({'href': value})
  1264.  
  1265.     def _start_admin_errorreportsto(self, attrsD):
  1266.         self.push('errorreportsto', 1)
  1267.         value = self._getAttribute(attrsD, 'rdf:resource')
  1268.         if value:
  1269.             self.elementstack[-1][2].append(value)
  1270.         self.pop('errorreportsto')
  1271.         
  1272.     def _start_summary(self, attrsD):
  1273.         context = self._getContext()
  1274.         if context.has_key('summary'):
  1275.             self._summaryKey = 'content'
  1276.             self._start_content(attrsD)
  1277.         else:
  1278.             self._summaryKey = 'summary'
  1279.             self.pushContent(self._summaryKey, attrsD, 'text/plain', 1)
  1280.     _start_itunes_summary = _start_summary
  1281.  
  1282.     def _end_summary(self):
  1283.         if self._summaryKey == 'content':
  1284.             self._end_content()
  1285.         else:
  1286.             self.popContent(self._summaryKey or 'summary')
  1287.         self._summaryKey = None
  1288.     _end_itunes_summary = _end_summary
  1289.         
  1290.     def _start_enclosure(self, attrsD):
  1291.         attrsD = self._itsAnHrefDamnIt(attrsD)
  1292.         self._getContext().setdefault('enclosures', []).append(FeedParserDict(attrsD))
  1293.         href = attrsD.get('href')
  1294.         if href:
  1295.             context = self._getContext()
  1296.             if not context.get('id'):
  1297.                 context['id'] = href
  1298.             
  1299.     def _start_source(self, attrsD):
  1300.         self.insource = 1
  1301.  
  1302.     def _end_source(self):
  1303.         self.insource = 0
  1304.         self._getContext()['source'] = copy.deepcopy(self.sourcedata)
  1305.         self.sourcedata.clear()
  1306.  
  1307.     def _start_content(self, attrsD):
  1308.         self.pushContent('content', attrsD, 'text/plain', 1)
  1309.         src = attrsD.get('src')
  1310.         if src:
  1311.             self.contentparams['src'] = src
  1312.         self.push('content', 1)
  1313.  
  1314.     def _start_prodlink(self, attrsD):
  1315.         self.pushContent('content', attrsD, 'text/html', 1)
  1316.  
  1317.     def _start_body(self, attrsD):
  1318.         self.pushContent('content', attrsD, 'application/xhtml+xml', 1)
  1319.     _start_xhtml_body = _start_body
  1320.  
  1321.     def _start_content_encoded(self, attrsD):
  1322.         self.pushContent('content', attrsD, 'text/html', 1)
  1323.     _start_fullitem = _start_content_encoded
  1324.  
  1325.     def _end_content(self):
  1326.         copyToDescription = self.mapContentType(self.contentparams.get('type')) in (['text/plain'] + self.html_types)
  1327.         value = self.popContent('content')
  1328.         if copyToDescription:
  1329.             self._save('description', value)
  1330.     _end_body = _end_content
  1331.     _end_xhtml_body = _end_content
  1332.     _end_content_encoded = _end_content
  1333.     _end_fullitem = _end_content
  1334.     _end_prodlink = _end_content
  1335.  
  1336.     def _start_itunes_image(self, attrsD):
  1337.         self.push('itunes_image', 0)
  1338.         self._getContext()['image'] = FeedParserDict({'href': attrsD.get('href')})
  1339.     _start_itunes_link = _start_itunes_image
  1340.         
  1341.     def _end_itunes_block(self):
  1342.         value = self.pop('itunes_block', 0)
  1343.         self._getContext()['itunes_block'] = (value == 'yes') and 1 or 0
  1344.  
  1345.     def _end_itunes_explicit(self):
  1346.         value = self.pop('itunes_explicit', 0)
  1347.         self._getContext()['itunes_explicit'] = (value == 'yes') and 1 or 0
  1348.  
  1349. if _XML_AVAILABLE:
  1350.     class _StrictFeedParser(_FeedParserMixin, xml.sax.handler.ContentHandler):
  1351.         def __init__(self, baseuri, baselang, encoding):
  1352.             if _debug: sys.stderr.write('trying StrictFeedParser\n')
  1353.             xml.sax.handler.ContentHandler.__init__(self)
  1354.             _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1355.             self.bozo = 0
  1356.             self.exc = None
  1357.         
  1358.         def startPrefixMapping(self, prefix, uri):
  1359.             self.trackNamespace(prefix, uri)
  1360.         
  1361.         def startElementNS(self, name, qname, attrs):
  1362.             namespace, localname = name
  1363.             lowernamespace = str(namespace or '').lower()
  1364.             if lowernamespace.find('backend.userland.com/rss') <> -1:
  1365.                 # match any backend.userland.com namespace
  1366.                 namespace = 'http://backend.userland.com/rss'
  1367.                 lowernamespace = namespace
  1368.             if qname and qname.find(':') > 0:
  1369.                 givenprefix = qname.split(':')[0]
  1370.             else:
  1371.                 givenprefix = None
  1372.             prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1373.             if givenprefix and (prefix == None or (prefix == '' and lowernamespace == '')) and not self.namespacesInUse.has_key(givenprefix):
  1374.                     raise UndeclaredNamespace, "'%s' is not associated with a namespace" % givenprefix
  1375.             if prefix:
  1376.                 localname = prefix + ':' + localname
  1377.             localname = str(localname).lower()
  1378.             if _debug: sys.stderr.write('startElementNS: qname = %s, namespace = %s, givenprefix = %s, prefix = %s, attrs = %s, localname = %s\n' % (qname, namespace, givenprefix, prefix, attrs.items(), localname))
  1379.  
  1380.             # qname implementation is horribly broken in Python 2.1 (it
  1381.             # doesn't report any), and slightly broken in Python 2.2 (it
  1382.             # doesn't report the xml: namespace). So we match up namespaces
  1383.             # with a known list first, and then possibly override them with
  1384.             # the qnames the SAX parser gives us (if indeed it gives us any
  1385.             # at all).  Thanks to MatejC for helping me test this and
  1386.             # tirelessly telling me that it didn't work yet.
  1387.             attrsD = {}
  1388.             for (namespace, attrlocalname), attrvalue in attrs._attrs.items():
  1389.                 lowernamespace = (namespace or '').lower()
  1390.                 prefix = self._matchnamespaces.get(lowernamespace, '')
  1391.                 if prefix:
  1392.                     attrlocalname = prefix + ':' + attrlocalname
  1393.                 attrsD[str(attrlocalname).lower()] = attrvalue
  1394.             for qname in attrs.getQNames():
  1395.                 attrsD[str(qname).lower()] = attrs.getValueByQName(qname)
  1396.             self.unknown_starttag(localname, attrsD.items())
  1397.  
  1398.         def characters(self, text):
  1399.             self.handle_data(text)
  1400.  
  1401.         def endElementNS(self, name, qname):
  1402.             namespace, localname = name
  1403.             lowernamespace = str(namespace or '').lower()
  1404.             if qname and qname.find(':') > 0:
  1405.                 givenprefix = qname.split(':')[0]
  1406.             else:
  1407.                 givenprefix = ''
  1408.             prefix = self._matchnamespaces.get(lowernamespace, givenprefix)
  1409.             if prefix:
  1410.                 localname = prefix + ':' + localname
  1411.             localname = str(localname).lower()
  1412.             self.unknown_endtag(localname)
  1413.  
  1414.         def error(self, exc):
  1415.             self.bozo = 1
  1416.             self.exc = exc
  1417.             
  1418.         def fatalError(self, exc):
  1419.             self.error(exc)
  1420.             raise exc
  1421.  
  1422. class _BaseHTMLProcessor(sgmllib.SGMLParser):
  1423.     elements_no_end_tag = ['area', 'base', 'basefont', 'br', 'col', 'frame', 'hr',
  1424.       'img', 'input', 'isindex', 'link', 'meta', 'param']
  1425.     
  1426.     def __init__(self, encoding):
  1427.         self.encoding = encoding
  1428.         if _debug: sys.stderr.write('entering BaseHTMLProcessor, encoding=%s\n' % self.encoding)
  1429.         sgmllib.SGMLParser.__init__(self)
  1430.         
  1431.     def reset(self):
  1432.         self.pieces = []
  1433.         sgmllib.SGMLParser.reset(self)
  1434.  
  1435.     def _shorttag_replace(self, match):
  1436.         tag = match.group(1)
  1437.         if tag in self.elements_no_end_tag:
  1438.             return '<' + tag + ' />'
  1439.         else:
  1440.             return '<' + tag + '></' + tag + '>'
  1441.         
  1442.     def feed(self, data):
  1443.         data = re.compile(r'<!((?!DOCTYPE|--|\[))', re.IGNORECASE).sub(r'<!\1', data)
  1444.         #data = re.sub(r'<(\S+?)\s*?/>', self._shorttag_replace, data) # bug [ 1399464 ] Bad regexp for _shorttag_replace
  1445.         data = re.sub(r'<([^<\s]+?)\s*/>', self._shorttag_replace, data) 
  1446.         data = data.replace(''', "'")
  1447.         data = data.replace('"', '"')
  1448.         if self.encoding and type(data) == type(u''):
  1449.             data = data.encode(self.encoding)
  1450.         sgmllib.SGMLParser.feed(self, data)
  1451.  
  1452.     def normalize_attrs(self, attrs):
  1453.         # utility method to be called by descendants
  1454.         attrs = [(k.lower(), v) for k, v in attrs]
  1455.         attrs = [(k, k in ('rel', 'type') and v.lower() or v) for k, v in attrs]
  1456.         return attrs
  1457.  
  1458.     def unknown_starttag(self, tag, attrs):
  1459.         # called for each start tag
  1460.         # attrs is a list of (attr, value) tuples
  1461.         # e.g. for <pre class='screen'>, tag='pre', attrs=[('class', 'screen')]
  1462.         if _debug: sys.stderr.write('_BaseHTMLProcessor, unknown_starttag, tag=%s\n' % tag)
  1463.         uattrs = []
  1464.         # thanks to Kevin Marks for this breathtaking hack to deal with (valid) high-bit attribute values in UTF-8 feeds
  1465.         for key, value in attrs:
  1466.             if type(value) != type(u''):
  1467.                 value = unicode(value, self.encoding, errors='replace')
  1468.             uattrs.append((unicode(key, self.encoding), value))
  1469.         strattrs = u''.join([u' %s="%s"' % (key, value) for key, value in uattrs]).encode(self.encoding)
  1470.         if tag in self.elements_no_end_tag:
  1471.             self.pieces.append('<%(tag)s%(strattrs)s />' % locals())
  1472.         else:
  1473.             self.pieces.append('<%(tag)s%(strattrs)s>' % locals())
  1474.  
  1475.     def unknown_endtag(self, tag):
  1476.         # called for each end tag, e.g. for </pre>, tag will be 'pre'
  1477.         # Reconstruct the original end tag.
  1478.         if tag not in self.elements_no_end_tag:
  1479.             self.pieces.append("</%(tag)s>" % locals())
  1480.  
  1481.     def handle_charref(self, ref):
  1482.         # called for each character reference, e.g. for ' ', ref will be '160'
  1483.         # Reconstruct the original character reference.
  1484.         self.pieces.append('&#%(ref)s;' % locals())
  1485.         
  1486.     def handle_entityref(self, ref):
  1487.         # called for each entity reference, e.g. for '©', ref will be 'copy'
  1488.         # Reconstruct the original entity reference.
  1489.         self.pieces.append('&%(ref)s;' % locals())
  1490.  
  1491.     def handle_data(self, text):
  1492.         # called for each block of plain text, i.e. outside of any tag and
  1493.         # not containing any character or entity references
  1494.         # Store the original text verbatim.
  1495.         if _debug: sys.stderr.write('_BaseHTMLProcessor, handle_text, text=%s\n' % text)
  1496.         self.pieces.append(text)
  1497.         
  1498.     def handle_comment(self, text):
  1499.         # called for each HTML comment, e.g. <!-- insert Javascript code here -->
  1500.         # Reconstruct the original comment.
  1501.         self.pieces.append('<!--%(text)s-->' % locals())
  1502.         
  1503.     def handle_pi(self, text):
  1504.         # called for each processing instruction, e.g. <?instruction>
  1505.         # Reconstruct original processing instruction.
  1506.         self.pieces.append('<?%(text)s>' % locals())
  1507.  
  1508.     def handle_decl(self, text):
  1509.         # called for the DOCTYPE, if present, e.g.
  1510.         # <!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
  1511.         #     "http://www.w3.org/TR/html4/loose.dtd">
  1512.         # Reconstruct original DOCTYPE
  1513.         self.pieces.append('<!%(text)s>' % locals())
  1514.         
  1515.     _new_declname_match = re.compile(r'[a-zA-Z][-_.a-zA-Z0-9:]*\s*').match
  1516.     def _scan_name(self, i, declstartpos):
  1517.         rawdata = self.rawdata
  1518.         n = len(rawdata)
  1519.         if i == n:
  1520.             return None, -1
  1521.         m = self._new_declname_match(rawdata, i)
  1522.         if m:
  1523.             s = m.group()
  1524.             name = s.strip()
  1525.             if (i + len(s)) == n:
  1526.                 return None, -1  # end of buffer
  1527.             return name.lower(), m.end()
  1528.         else:
  1529.             self.handle_data(rawdata)
  1530. #            self.updatepos(declstartpos, i)
  1531.             return None, -1
  1532.  
  1533.     def output(self):
  1534.         '''Return processed HTML as a single string'''
  1535.         return ''.join([str(p) for p in self.pieces])
  1536.  
  1537. class _LooseFeedParser(_FeedParserMixin, _BaseHTMLProcessor):
  1538.     def __init__(self, baseuri, baselang, encoding):
  1539.         sgmllib.SGMLParser.__init__(self)
  1540.         _FeedParserMixin.__init__(self, baseuri, baselang, encoding)
  1541.  
  1542.     def decodeEntities(self, element, data):
  1543.         data = data.replace('<', '<')
  1544.         data = data.replace('<', '<')
  1545.         data = data.replace('>', '>')
  1546.         data = data.replace('>', '>')
  1547.         data = data.replace('&', '&')
  1548.         data = data.replace('&', '&')
  1549.         data = data.replace('"', '"')
  1550.         data = data.replace('"', '"')
  1551.         data = data.replace(''', ''')
  1552.         data = data.replace(''', ''')
  1553.         if self.contentparams.has_key('type') and not self.contentparams.get('type', 'xml').endswith('xml'):
  1554.             data = data.replace('<', '<')
  1555.             data = data.replace('>', '>')
  1556.             data = data.replace('&', '&')
  1557.             data = data.replace('"', '"')
  1558.             data = data.replace(''', "'")
  1559.         return data
  1560.         
  1561. class _RelativeURIResolver(_BaseHTMLProcessor):
  1562.     relative_uris = [('a', 'href'),
  1563.                      ('applet', 'codebase'),
  1564.                      ('area', 'href'),
  1565.                      ('blockquote', 'cite'),
  1566.                      ('body', 'background'),
  1567.                      ('del', 'cite'),
  1568.                      ('form', 'action'),
  1569.                      ('frame', 'longdesc'),
  1570.                      ('frame', 'src'),
  1571.                      ('iframe', 'longdesc'),
  1572.                      ('iframe', 'src'),
  1573.                      ('head', 'profile'),
  1574.                      ('img', 'longdesc'),
  1575.                      ('img', 'src'),
  1576.                      ('img', 'usemap'),
  1577.                      ('input', 'src'),
  1578.                      ('input', 'usemap'),
  1579.                      ('ins', 'cite'),
  1580.                      ('link', 'href'),
  1581.                      ('object', 'classid'),
  1582.                      ('object', 'codebase'),
  1583.                      ('object', 'data'),
  1584.                      ('object', 'usemap'),
  1585.                      ('q', 'cite'),
  1586.                      ('script', 'src')]
  1587.  
  1588.     def __init__(self, baseuri, encoding):
  1589.         _BaseHTMLProcessor.__init__(self, encoding)
  1590.         self.baseuri = baseuri
  1591.  
  1592.     def resolveURI(self, uri):
  1593.         return _urljoin(self.baseuri, uri)
  1594.     
  1595.     def unknown_starttag(self, tag, attrs):
  1596.         attrs = self.normalize_attrs(attrs)
  1597.         attrs = [(key, ((tag, key) in self.relative_uris) and self.resolveURI(value) or value) for key, value in attrs]
  1598.         _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1599.         
  1600. def _resolveRelativeURIs(htmlSource, baseURI, encoding):
  1601.     if _debug: sys.stderr.write('entering _resolveRelativeURIs\n')
  1602.     p = _RelativeURIResolver(baseURI, encoding)
  1603.     p.feed(htmlSource)
  1604.     return p.output()
  1605.  
  1606. class _HTMLSanitizer(_BaseHTMLProcessor):
  1607.     acceptable_elements = ['a', 'abbr', 'acronym', 'address', 'area', 'b', 'big',
  1608.       'blockquote', 'br', 'button', 'caption', 'center', 'cite', 'code', 'col',
  1609.       'colgroup', 'dd', 'del', 'dfn', 'dir', 'div', 'dl', 'dt', 'em', 'fieldset',
  1610.       'font', 'form', 'h1', 'h2', 'h3', 'h4', 'h5', 'h6', 'hr', 'i', 'img', 'input',
  1611.       'ins', 'kbd', 'label', 'legend', 'li', 'map', 'menu', 'ol', 'optgroup',
  1612.       'option', 'p', 'pre', 'q', 's', 'samp', 'select', 'small', 'span', 'strike',
  1613.       'strong', 'sub', 'sup', 'table', 'tbody', 'td', 'textarea', 'tfoot', 'th',
  1614.       'thead', 'tr', 'tt', 'u', 'ul', 'var']
  1615.  
  1616.     acceptable_attributes = ['abbr', 'accept', 'accept-charset', 'accesskey',
  1617.       'action', 'align', 'alt', 'axis', 'border', 'cellpadding', 'cellspacing',
  1618.       'char', 'charoff', 'charset', 'checked', 'cite', 'class', 'clear', 'cols',
  1619.       'colspan', 'color', 'compact', 'coords', 'datetime', 'dir', 'disabled',
  1620.       'enctype', 'for', 'frame', 'headers', 'height', 'href', 'hreflang', 'hspace',
  1621.       'id', 'ismap', 'label', 'lang', 'longdesc', 'maxlength', 'media', 'method',
  1622.       'multiple', 'name', 'nohref', 'noshade', 'nowrap', 'prompt', 'readonly',
  1623.       'rel', 'rev', 'rows', 'rowspan', 'rules', 'scope', 'selected', 'shape', 'size',
  1624.       'span', 'src', 'start', 'summary', 'tabindex', 'target', 'title', 'type',
  1625.       'usemap', 'valign', 'value', 'vspace', 'width']
  1626.  
  1627.     unacceptable_elements_with_end_tag = ['script', 'applet']
  1628.  
  1629.     def reset(self):
  1630.         _BaseHTMLProcessor.reset(self)
  1631.         self.unacceptablestack = 0
  1632.         
  1633.     def unknown_starttag(self, tag, attrs):
  1634.         if not tag in self.acceptable_elements:
  1635.             if tag in self.unacceptable_elements_with_end_tag:
  1636.                 self.unacceptablestack += 1
  1637.             return
  1638.         attrs = self.normalize_attrs(attrs)
  1639.         attrs = [(key, value) for key, value in attrs if key in self.acceptable_attributes]
  1640.         _BaseHTMLProcessor.unknown_starttag(self, tag, attrs)
  1641.         
  1642.     def unknown_endtag(self, tag):
  1643.         if not tag in self.acceptable_elements:
  1644.             if tag in self.unacceptable_elements_with_end_tag:
  1645.                 self.unacceptablestack -= 1
  1646.             return
  1647.         _BaseHTMLProcessor.unknown_endtag(self, tag)
  1648.  
  1649.     def handle_pi(self, text):
  1650.         pass
  1651.  
  1652.     def handle_decl(self, text):
  1653.         pass
  1654.  
  1655.     def handle_data(self, text):
  1656.         if not self.unacceptablestack:
  1657.             _BaseHTMLProcessor.handle_data(self, text)
  1658.  
  1659. def _sanitizeHTML(htmlSource, encoding):
  1660.     p = _HTMLSanitizer(encoding)
  1661.     p.feed(htmlSource)
  1662.     data = p.output()
  1663.     if TIDY_MARKUP:
  1664.         # loop through list of preferred Tidy interfaces looking for one that's installed,
  1665.         # then set up a common _tidy function to wrap the interface-specific API.
  1666.         _tidy = None
  1667.         for tidy_interface in PREFERRED_TIDY_INTERFACES:
  1668.             try:
  1669.                 if tidy_interface == "uTidy":
  1670.                     from tidy import parseString as _utidy
  1671.                     def _tidy(data, **kwargs):
  1672.                         return str(_utidy(data, **kwargs))
  1673.                     break
  1674.                 elif tidy_interface == "mxTidy":
  1675.                     from mx.Tidy import Tidy as _mxtidy
  1676.                     def _tidy(data, **kwargs):
  1677.                         nerrors, nwarnings, data, errordata = _mxtidy.tidy(data, **kwargs)
  1678.                         return data
  1679.                     break
  1680.             except:
  1681.                 pass
  1682.         if _tidy:
  1683.             utf8 = type(data) == type(u'')
  1684.             if utf8:
  1685.                 data = data.encode('utf-8')
  1686.             data = _tidy(data, output_xhtml=1, numeric_entities=1, wrap=0, char_encoding="utf8")
  1687.             if utf8:
  1688.                 data = unicode(data, 'utf-8')
  1689.             if data.count('<body'):
  1690.                 data = data.split('<body', 1)[1]
  1691.                 if data.count('>'):
  1692.                     data = data.split('>', 1)[1]
  1693.             if data.count('</body'):
  1694.                 data = data.split('</body', 1)[0]
  1695.     data = data.strip().replace('\r\n', '\n')
  1696.     return data
  1697.  
  1698. class _FeedURLHandler(urllib2.HTTPDigestAuthHandler, urllib2.HTTPRedirectHandler, urllib2.HTTPDefaultErrorHandler):
  1699.     def http_error_default(self, req, fp, code, msg, headers):
  1700.         if ((code / 100) == 3) and (code != 304):
  1701.             return self.http_error_302(req, fp, code, msg, headers)
  1702.         infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1703.         infourl.status = code
  1704.         return infourl
  1705.  
  1706.     def http_error_302(self, req, fp, code, msg, headers):
  1707.         if headers.dict.has_key('location'):
  1708.             infourl = urllib2.HTTPRedirectHandler.http_error_302(self, req, fp, code, msg, headers)
  1709.         else:
  1710.             infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1711.         if not hasattr(infourl, 'status'):
  1712.             infourl.status = code
  1713.         return infourl
  1714.  
  1715.     def http_error_301(self, req, fp, code, msg, headers):
  1716.         if headers.dict.has_key('location'):
  1717.             infourl = urllib2.HTTPRedirectHandler.http_error_301(self, req, fp, code, msg, headers)
  1718.         else:
  1719.             infourl = urllib.addinfourl(fp, headers, req.get_full_url())
  1720.         if not hasattr(infourl, 'status'):
  1721.             infourl.status = code
  1722.         return infourl
  1723.  
  1724.     http_error_300 = http_error_302
  1725.     http_error_303 = http_error_302
  1726.     http_error_307 = http_error_302
  1727.         
  1728.     def http_error_401(self, req, fp, code, msg, headers):
  1729.         # Check if
  1730.         # - server requires digest auth, AND
  1731.         # - we tried (unsuccessfully) with basic auth, AND
  1732.         # - we're using Python 2.3.3 or later (digest auth is irreparably broken in earlier versions)
  1733.         # If all conditions hold, parse authentication information
  1734.         # out of the Authorization header we sent the first time
  1735.         # (for the username and password) and the WWW-Authenticate
  1736.         # header the server sent back (for the realm) and retry
  1737.         # the request with the appropriate digest auth headers instead.
  1738.         # This evil genius hack has been brought to you by Aaron Swartz.
  1739.         host = urlparse.urlparse(req.get_full_url())[1]
  1740.         try:
  1741.             assert sys.version.split()[0] >= '2.3.3'
  1742.             assert base64 != None
  1743.             user, passw = base64.decodestring(req.headers['Authorization'].split(' ')[1]).split(':')
  1744.             realm = re.findall('realm="([^"]*)"', headers['WWW-Authenticate'])[0]
  1745.             self.add_password(realm, host, user, passw)
  1746.             retry = self.http_error_auth_reqed('www-authenticate', host, req, headers)
  1747.             self.reset_retry_count()
  1748.             return retry
  1749.         except:
  1750.             return self.http_error_default(req, fp, code, msg, headers)
  1751.  
  1752. def _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers):
  1753.     """URL, filename, or string --> stream
  1754.  
  1755.     This function lets you define parsers that take any input source
  1756.     (URL, pathname to local or network file, or actual data as a string)
  1757.     and deal with it in a uniform manner.  Returned object is guaranteed
  1758.     to have all the basic stdio read methods (read, readline, readlines).
  1759.     Just .close() the object when you're done with it.
  1760.  
  1761.     If the etag argument is supplied, it will be used as the value of an
  1762.     If-None-Match request header.
  1763.  
  1764.     If the modified argument is supplied, it must be a tuple of 9 integers
  1765.     as returned by gmtime() in the standard Python time module. This MUST
  1766.     be in GMT (Greenwich Mean Time). The formatted date/time will be used
  1767.     as the value of an If-Modified-Since request header.
  1768.  
  1769.     If the agent argument is supplied, it will be used as the value of a
  1770.     User-Agent request header.
  1771.  
  1772.     If the referrer argument is supplied, it will be used as the value of a
  1773.     Referer[sic] request header.
  1774.  
  1775.     If handlers is supplied, it is a list of handlers used to build a
  1776.     urllib2 opener.
  1777.     """
  1778.  
  1779.     if hasattr(url_file_stream_or_string, 'read'):
  1780.         return url_file_stream_or_string
  1781.  
  1782.     if url_file_stream_or_string == '-':
  1783.         return sys.stdin
  1784.  
  1785.     if urlparse.urlparse(url_file_stream_or_string)[0] in ('http', 'https', 'ftp'):
  1786.         if not agent:
  1787.             agent = USER_AGENT
  1788.         # test for inline user:password for basic auth
  1789.         auth = None
  1790.         if base64:
  1791.             urltype, rest = urllib.splittype(url_file_stream_or_string)
  1792.             realhost, rest = urllib.splithost(rest)
  1793.             if realhost:
  1794.                 user_passwd, realhost = urllib.splituser(realhost)
  1795.                 if user_passwd:
  1796.                     url_file_stream_or_string = '%s://%s%s' % (urltype, realhost, rest)
  1797.                     auth = base64.encodestring(user_passwd).strip()
  1798.         # try to open with urllib2 (to use optional headers)
  1799.         request = urllib2.Request(url_file_stream_or_string)
  1800.         request.add_header('User-Agent', agent)
  1801.         if etag:
  1802.             request.add_header('If-None-Match', etag)
  1803.         if modified:
  1804.             # format into an RFC 1123-compliant timestamp. We can't use
  1805.             # time.strftime() since the %a and %b directives can be affected
  1806.             # by the current locale, but RFC 2616 states that dates must be
  1807.             # in English.
  1808.             short_weekdays = ['Mon', 'Tue', 'Wed', 'Thu', 'Fri', 'Sat', 'Sun']
  1809.             months = ['Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec']
  1810.             request.add_header('If-Modified-Since', '%s, %02d %s %04d %02d:%02d:%02d GMT' % (short_weekdays[modified[6]], modified[2], months[modified[1] - 1], modified[0], modified[3], modified[4], modified[5]))
  1811.         if referrer:
  1812.             request.add_header('Referer', referrer)
  1813.         if gzip and zlib:
  1814.             request.add_header('Accept-encoding', 'gzip, deflate')
  1815.         elif gzip:
  1816.             request.add_header('Accept-encoding', 'gzip')
  1817.         elif zlib:
  1818.             request.add_header('Accept-encoding', 'deflate')
  1819.         else:
  1820.             request.add_header('Accept-encoding', '')
  1821.         if auth:
  1822.             request.add_header('Authorization', 'Basic %s' % auth)
  1823.         if ACCEPT_HEADER:
  1824.             request.add_header('Accept', ACCEPT_HEADER)
  1825.         request.add_header('A-IM', 'feed') # RFC 3229 support
  1826.         opener = apply(urllib2.build_opener, tuple(handlers + [_FeedURLHandler()]))
  1827.         opener.addheaders = [] # RMK - must clear so we only send our custom User-Agent
  1828.         try:
  1829.             return opener.open(request)
  1830.         finally:
  1831.             opener.close() # JohnD
  1832.     
  1833.     # try to open with native open function (if url_file_stream_or_string is a filename)
  1834.     try:
  1835.         return open(url_file_stream_or_string)
  1836.     except:
  1837.         pass
  1838.  
  1839.     # treat url_file_stream_or_string as string
  1840.     return _StringIO(str(url_file_stream_or_string))
  1841.  
  1842. _date_handlers = []
  1843. def registerDateHandler(func):
  1844.     '''Register a date handler function (takes string, returns 9-tuple date in GMT)'''
  1845.     _date_handlers.insert(0, func)
  1846.     
  1847. # ISO-8601 date parsing routines written by Fazal Majid.
  1848. # The ISO 8601 standard is very convoluted and irregular - a full ISO 8601
  1849. # parser is beyond the scope of feedparser and would be a worthwhile addition
  1850. # to the Python library.
  1851. # A single regular expression cannot parse ISO 8601 date formats into groups
  1852. # as the standard is highly irregular (for instance is 030104 2003-01-04 or
  1853. # 0301-04-01), so we use templates instead.
  1854. # Please note the order in templates is significant because we need a
  1855. # greedy match.
  1856. _iso8601_tmpl = ['YYYY-?MM-?DD', 'YYYY-MM', 'YYYY-?OOO',
  1857.                 'YY-?MM-?DD', 'YY-?OOO', 'YYYY', 
  1858.                 '-YY-?MM', '-OOO', '-YY',
  1859.                 '--MM-?DD', '--MM',
  1860.                 '---DD',
  1861.                 'CC', '']
  1862. _iso8601_re = [
  1863.     tmpl.replace(
  1864.     'YYYY', r'(?P<year>\d{4})').replace(
  1865.     'YY', r'(?P<year>\d\d)').replace(
  1866.     'MM', r'(?P<month>[01]\d)').replace(
  1867.     'DD', r'(?P<day>[0123]\d)').replace(
  1868.     'OOO', r'(?P<ordinal>[0123]\d\d)').replace(
  1869.     'CC', r'(?P<century>\d\d$)')
  1870.     + r'(T?(?P<hour>\d{2}):(?P<minute>\d{2})'
  1871.     + r'(:(?P<second>\d{2}))?'
  1872.     + r'(?P<tz>[+-](?P<tzhour>\d{2})(:(?P<tzmin>\d{2}))?|Z)?)?'
  1873.     for tmpl in _iso8601_tmpl]
  1874. del tmpl
  1875. _iso8601_matches = [re.compile(regex).match for regex in _iso8601_re]
  1876. del regex
  1877. def _parse_date_iso8601(dateString):
  1878.     '''Parse a variety of ISO-8601-compatible formats like 20040105'''
  1879.     m = None
  1880.     for _iso8601_match in _iso8601_matches:
  1881.         m = _iso8601_match(dateString)
  1882.         if m: break
  1883.     if not m: return
  1884.     if m.span() == (0, 0): return
  1885.     params = m.groupdict()
  1886.     ordinal = params.get('ordinal', 0)
  1887.     if ordinal:
  1888.         ordinal = int(ordinal)
  1889.     else:
  1890.         ordinal = 0
  1891.     year = params.get('year', '--')
  1892.     if not year or year == '--':
  1893.         year = time.gmtime()[0]
  1894.     elif len(year) == 2:
  1895.         # ISO 8601 assumes current century, i.e. 93 -> 2093, NOT 1993
  1896.         year = 100 * int(time.gmtime()[0] / 100) + int(year)
  1897.     else:
  1898.         year = int(year)
  1899.     month = params.get('month', '-')
  1900.     if not month or month == '-':
  1901.         # ordinals are NOT normalized by mktime, we simulate them
  1902.         # by setting month=1, day=ordinal
  1903.         if ordinal:
  1904.             month = 1
  1905.         else:
  1906.             month = time.gmtime()[1]
  1907.     month = int(month)
  1908.     day = params.get('day', 0)
  1909.     if not day:
  1910.         # see above
  1911.         if ordinal:
  1912.             day = ordinal
  1913.         elif params.get('century', 0) or \
  1914.                  params.get('year', 0) or params.get('month', 0):
  1915.             day = 1
  1916.         else:
  1917.             day = time.gmtime()[2]
  1918.     else:
  1919.         day = int(day)
  1920.     # special case of the century - is the first year of the 21st century
  1921.     # 2000 or 2001 ? The debate goes on...
  1922.     if 'century' in params.keys():
  1923.         year = (int(params['century']) - 1) * 100 + 1
  1924.     # in ISO 8601 most fields are optional
  1925.     for field in ['hour', 'minute', 'second', 'tzhour', 'tzmin']:
  1926.         if not params.get(field, None):
  1927.             params[field] = 0
  1928.     hour = int(params.get('hour', 0))
  1929.     minute = int(params.get('minute', 0))
  1930.     second = int(params.get('second', 0))
  1931.     # weekday is normalized by mktime(), we can ignore it
  1932.     weekday = 0
  1933.     # daylight savings is complex, but not needed for feedparser's purposes
  1934.     # as time zones, if specified, include mention of whether it is active
  1935.     # (e.g. PST vs. PDT, CET). Using -1 is implementation-dependent and
  1936.     # and most implementations have DST bugs
  1937.     daylight_savings_flag = 0
  1938.     tm = [year, month, day, hour, minute, second, weekday,
  1939.           ordinal, daylight_savings_flag]
  1940.     # ISO 8601 time zone adjustments
  1941.     tz = params.get('tz')
  1942.     if tz and tz != 'Z':
  1943.         if tz[0] == '-':
  1944.             tm[3] += int(params.get('tzhour', 0))
  1945.             tm[4] += int(params.get('tzmin', 0))
  1946.         elif tz[0] == '+':
  1947.             tm[3] -= int(params.get('tzhour', 0))
  1948.             tm[4] -= int(params.get('tzmin', 0))
  1949.         else:
  1950.             return None
  1951.     # Python's time.mktime() is a wrapper around the ANSI C mktime(3c)
  1952.     # which is guaranteed to normalize d/m/y/h/m/s.
  1953.     # Many implementations have bugs, but we'll pretend they don't.
  1954.     return time.localtime(time.mktime(tm))
  1955. registerDateHandler(_parse_date_iso8601)
  1956.     
  1957. # 8-bit date handling routines written by ytrewq1.
  1958. _korean_year  = u'\ub144' # b3e2 in euc-kr
  1959. _korean_month = u'\uc6d4' # bff9 in euc-kr
  1960. _korean_day   = u'\uc77c' # c0cf in euc-kr
  1961. _korean_am    = u'\uc624\uc804' # bfc0 c0fc in euc-kr
  1962. _korean_pm    = u'\uc624\ud6c4' # bfc0 c8c4 in euc-kr
  1963.  
  1964. _korean_onblog_date_re = \
  1965.     re.compile('(\d{4})%s\s+(\d{2})%s\s+(\d{2})%s\s+(\d{2}):(\d{2}):(\d{2})' % \
  1966.                (_korean_year, _korean_month, _korean_day))
  1967. _korean_nate_date_re = \
  1968.     re.compile(u'(\d{4})-(\d{2})-(\d{2})\s+(%s|%s)\s+(\d{,2}):(\d{,2}):(\d{,2})' % \
  1969.                (_korean_am, _korean_pm))
  1970. def _parse_date_onblog(dateString):
  1971.     '''Parse a string according to the OnBlog 8-bit date format'''
  1972.     m = _korean_onblog_date_re.match(dateString)
  1973.     if not m: return
  1974.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  1975.                 {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  1976.                  'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  1977.                  'zonediff': '+09:00'}
  1978.     if _debug: sys.stderr.write('OnBlog date parsed as: %s\n' % w3dtfdate)
  1979.     return _parse_date_w3dtf(w3dtfdate)
  1980. registerDateHandler(_parse_date_onblog)
  1981.  
  1982. def _parse_date_nate(dateString):
  1983.     '''Parse a string according to the Nate 8-bit date format'''
  1984.     m = _korean_nate_date_re.match(dateString)
  1985.     if not m: return
  1986.     hour = int(m.group(5))
  1987.     ampm = m.group(4)
  1988.     if (ampm == _korean_pm):
  1989.         hour += 12
  1990.     hour = str(hour)
  1991.     if len(hour) == 1:
  1992.         hour = '0' + hour
  1993.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  1994.                 {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  1995.                  'hour': hour, 'minute': m.group(6), 'second': m.group(7),\
  1996.                  'zonediff': '+09:00'}
  1997.     if _debug: sys.stderr.write('Nate date parsed as: %s\n' % w3dtfdate)
  1998.     return _parse_date_w3dtf(w3dtfdate)
  1999. registerDateHandler(_parse_date_nate)
  2000.  
  2001. _mssql_date_re = \
  2002.     re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})(\.\d+)?')
  2003. def _parse_date_mssql(dateString):
  2004.     '''Parse a string according to the MS SQL date format'''
  2005.     m = _mssql_date_re.match(dateString)
  2006.     if not m: return
  2007.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s:%(second)s%(zonediff)s' % \
  2008.                 {'year': m.group(1), 'month': m.group(2), 'day': m.group(3),\
  2009.                  'hour': m.group(4), 'minute': m.group(5), 'second': m.group(6),\
  2010.                  'zonediff': '+09:00'}
  2011.     if _debug: sys.stderr.write('MS SQL date parsed as: %s\n' % w3dtfdate)
  2012.     return _parse_date_w3dtf(w3dtfdate)
  2013. registerDateHandler(_parse_date_mssql)
  2014.  
  2015. # Unicode strings for Greek date strings
  2016. _greek_months = \
  2017.   { \
  2018.    u'\u0399\u03b1\u03bd': u'Jan',       # c9e1ed in iso-8859-7
  2019.    u'\u03a6\u03b5\u03b2': u'Feb',       # d6e5e2 in iso-8859-7
  2020.    u'\u039c\u03ac\u03ce': u'Mar',       # ccdcfe in iso-8859-7
  2021.    u'\u039c\u03b1\u03ce': u'Mar',       # cce1fe in iso-8859-7
  2022.    u'\u0391\u03c0\u03c1': u'Apr',       # c1f0f1 in iso-8859-7
  2023.    u'\u039c\u03ac\u03b9': u'May',       # ccdce9 in iso-8859-7
  2024.    u'\u039c\u03b1\u03ca': u'May',       # cce1fa in iso-8859-7
  2025.    u'\u039c\u03b1\u03b9': u'May',       # cce1e9 in iso-8859-7
  2026.    u'\u0399\u03bf\u03cd\u03bd': u'Jun', # c9effded in iso-8859-7
  2027.    u'\u0399\u03bf\u03bd': u'Jun',       # c9efed in iso-8859-7
  2028.    u'\u0399\u03bf\u03cd\u03bb': u'Jul', # c9effdeb in iso-8859-7
  2029.    u'\u0399\u03bf\u03bb': u'Jul',       # c9f9eb in iso-8859-7
  2030.    u'\u0391\u03cd\u03b3': u'Aug',       # c1fde3 in iso-8859-7
  2031.    u'\u0391\u03c5\u03b3': u'Aug',       # c1f5e3 in iso-8859-7
  2032.    u'\u03a3\u03b5\u03c0': u'Sep',       # d3e5f0 in iso-8859-7
  2033.    u'\u039f\u03ba\u03c4': u'Oct',       # cfeaf4 in iso-8859-7
  2034.    u'\u039d\u03bf\u03ad': u'Nov',       # cdefdd in iso-8859-7
  2035.    u'\u039d\u03bf\u03b5': u'Nov',       # cdefe5 in iso-8859-7
  2036.    u'\u0394\u03b5\u03ba': u'Dec',       # c4e5ea in iso-8859-7
  2037.   }
  2038.  
  2039. _greek_wdays = \
  2040.   { \
  2041.    u'\u039a\u03c5\u03c1': u'Sun', # caf5f1 in iso-8859-7
  2042.    u'\u0394\u03b5\u03c5': u'Mon', # c4e5f5 in iso-8859-7
  2043.    u'\u03a4\u03c1\u03b9': u'Tue', # d4f1e9 in iso-8859-7
  2044.    u'\u03a4\u03b5\u03c4': u'Wed', # d4e5f4 in iso-8859-7
  2045.    u'\u03a0\u03b5\u03bc': u'Thu', # d0e5ec in iso-8859-7
  2046.    u'\u03a0\u03b1\u03c1': u'Fri', # d0e1f1 in iso-8859-7
  2047.    u'\u03a3\u03b1\u03b2': u'Sat', # d3e1e2 in iso-8859-7   
  2048.   }
  2049.  
  2050. _greek_date_format_re = \
  2051.     re.compile(u'([^,]+),\s+(\d{2})\s+([^\s]+)\s+(\d{4})\s+(\d{2}):(\d{2}):(\d{2})\s+([^\s]+)')
  2052.  
  2053. def _parse_date_greek(dateString):
  2054.     '''Parse a string according to a Greek 8-bit date format.'''
  2055.     m = _greek_date_format_re.match(dateString)
  2056.     if not m: return
  2057.     try:
  2058.         wday = _greek_wdays[m.group(1)]
  2059.         month = _greek_months[m.group(3)]
  2060.     except:
  2061.         return
  2062.     rfc822date = '%(wday)s, %(day)s %(month)s %(year)s %(hour)s:%(minute)s:%(second)s %(zonediff)s' % \
  2063.                  {'wday': wday, 'day': m.group(2), 'month': month, 'year': m.group(4),\
  2064.                   'hour': m.group(5), 'minute': m.group(6), 'second': m.group(7),\
  2065.                   'zonediff': m.group(8)}
  2066.     if _debug: sys.stderr.write('Greek date parsed as: %s\n' % rfc822date)
  2067.     return _parse_date_rfc822(rfc822date)
  2068. registerDateHandler(_parse_date_greek)
  2069.  
  2070. # Unicode strings for Hungarian date strings
  2071. _hungarian_months = \
  2072.   { \
  2073.     u'janu\u00e1r':   u'01',  # e1 in iso-8859-2
  2074.     u'febru\u00e1ri': u'02',  # e1 in iso-8859-2
  2075.     u'm\u00e1rcius':  u'03',  # e1 in iso-8859-2
  2076.     u'\u00e1prilis':  u'04',  # e1 in iso-8859-2
  2077.     u'm\u00e1ujus':   u'05',  # e1 in iso-8859-2
  2078.     u'j\u00fanius':   u'06',  # fa in iso-8859-2
  2079.     u'j\u00falius':   u'07',  # fa in iso-8859-2
  2080.     u'augusztus':     u'08',
  2081.     u'szeptember':    u'09',
  2082.     u'okt\u00f3ber':  u'10',  # f3 in iso-8859-2
  2083.     u'november':      u'11',
  2084.     u'december':      u'12',
  2085.   }
  2086.  
  2087. _hungarian_date_format_re = \
  2088.   re.compile(u'(\d{4})-([^-]+)-(\d{,2})T(\d{,2}):(\d{2})((\+|-)(\d{,2}:\d{2}))')
  2089.  
  2090. def _parse_date_hungarian(dateString):
  2091.     '''Parse a string according to a Hungarian 8-bit date format.'''
  2092.     m = _hungarian_date_format_re.match(dateString)
  2093.     if not m: return
  2094.     try:
  2095.         month = _hungarian_months[m.group(2)]
  2096.         day = m.group(3)
  2097.         if len(day) == 1:
  2098.             day = '0' + day
  2099.         hour = m.group(4)
  2100.         if len(hour) == 1:
  2101.             hour = '0' + hour
  2102.     except:
  2103.         return
  2104.     w3dtfdate = '%(year)s-%(month)s-%(day)sT%(hour)s:%(minute)s%(zonediff)s' % \
  2105.                 {'year': m.group(1), 'month': month, 'day': day,\
  2106.                  'hour': hour, 'minute': m.group(5),\
  2107.                  'zonediff': m.group(6)}
  2108.     if _debug: sys.stderr.write('Hungarian date parsed as: %s\n' % w3dtfdate)
  2109.     return _parse_date_w3dtf(w3dtfdate)
  2110. registerDateHandler(_parse_date_hungarian)
  2111.  
  2112. # W3DTF-style date parsing adapted from PyXML xml.utils.iso8601, written by
  2113. # Drake and licensed under the Python license.  Removed all range checking
  2114. # for month, day, hour, minute, and second, since mktime will normalize
  2115. # these later
  2116. def _parse_date_w3dtf(dateString):
  2117.     def __extract_date(m):
  2118.         year = int(m.group('year'))
  2119.         if year < 100:
  2120.             year = 100 * int(time.gmtime()[0] / 100) + int(year)
  2121.         if year < 1000:
  2122.             return 0, 0, 0
  2123.         julian = m.group('julian')
  2124.         if julian:
  2125.             julian = int(julian)
  2126.             month = julian / 30 + 1
  2127.             day = julian % 30 + 1
  2128.             jday = None
  2129.             while jday != julian:
  2130.                 t = time.mktime((year, month, day, 0, 0, 0, 0, 0, 0))
  2131.                 jday = time.gmtime(t)[-2]
  2132.                 diff = abs(jday - julian)
  2133.                 if jday > julian:
  2134.                     if diff < day:
  2135.                         day = day - diff
  2136.                     else:
  2137.                         month = month - 1
  2138.                         day = 31
  2139.                 elif jday < julian:
  2140.                     if day + diff < 28:
  2141.                        day = day + diff
  2142.                     else:
  2143.                         month = month + 1
  2144.             return year, month, day
  2145.         month = m.group('month')
  2146.         day = 1
  2147.         if month is None:
  2148.             month = 1
  2149.         else:
  2150.             month = int(month)
  2151.             day = m.group('day')
  2152.             if day:
  2153.                 day = int(day)
  2154.             else:
  2155.                 day = 1
  2156.         return year, month, day
  2157.  
  2158.     def __extract_time(m):
  2159.         if not m:
  2160.             return 0, 0, 0
  2161.         hours = m.group('hours')
  2162.         if not hours:
  2163.             return 0, 0, 0
  2164.         hours = int(hours)
  2165.         minutes = int(m.group('minutes'))
  2166.         seconds = m.group('seconds')
  2167.         if seconds:
  2168.             seconds = int(seconds)
  2169.         else:
  2170.             seconds = 0
  2171.         return hours, minutes, seconds
  2172.  
  2173.     def __extract_tzd(m):
  2174.         '''Return the Time Zone Designator as an offset in seconds from UTC.'''
  2175.         if not m:
  2176.             return 0
  2177.         tzd = m.group('tzd')
  2178.         if not tzd:
  2179.             return 0
  2180.         if tzd == 'Z':
  2181.             return 0
  2182.         hours = int(m.group('tzdhours'))
  2183.         minutes = m.group('tzdminutes')
  2184.         if minutes:
  2185.             minutes = int(minutes)
  2186.         else:
  2187.             minutes = 0
  2188.         offset = (hours*60 + minutes) * 60
  2189.         if tzd[0] == '+':
  2190.             return -offset
  2191.         return offset
  2192.  
  2193.     __date_re = ('(?P<year>\d\d\d\d)'
  2194.                  '(?:(?P<dsep>-|)'
  2195.                  '(?:(?P<julian>\d\d\d)'
  2196.                  '|(?P<month>\d\d)(?:(?P=dsep)(?P<day>\d\d))?))?')
  2197.     __tzd_re = '(?P<tzd>[-+](?P<tzdhours>\d\d)(?::?(?P<tzdminutes>\d\d))|Z)'
  2198.     __tzd_rx = re.compile(__tzd_re)
  2199.     __time_re = ('(?P<hours>\d\d)(?P<tsep>:|)(?P<minutes>\d\d)'
  2200.                  '(?:(?P=tsep)(?P<seconds>\d\d(?:[.,]\d+)?))?'
  2201.                  + __tzd_re)
  2202.     __datetime_re = '%s(?:T%s)?' % (__date_re, __time_re)
  2203.     __datetime_rx = re.compile(__datetime_re)
  2204.     m = __datetime_rx.match(dateString)
  2205.     if (m is None) or (m.group() != dateString): return
  2206.     gmt = __extract_date(m) + __extract_time(m) + (0, 0, 0)
  2207.     if gmt[0] == 0: return
  2208.     return time.gmtime(time.mktime(gmt) + __extract_tzd(m) - time.timezone)
  2209. registerDateHandler(_parse_date_w3dtf)
  2210.  
  2211. def _parse_date_rfc822(dateString):
  2212.     '''Parse an RFC822, RFC1123, RFC2822, or asctime-style date'''
  2213.     data = dateString.split()
  2214.     if data[0][-1] in (',', '.') or data[0].lower() in rfc822._daynames:
  2215.         del data[0]
  2216.     if len(data) == 4:
  2217.         s = data[3]
  2218.         i = s.find('+')
  2219.         if i > 0:
  2220.             data[3:] = [s[:i], s[i+1:]]
  2221.         else:
  2222.             data.append('')
  2223.         dateString = " ".join(data)
  2224.     if len(data) < 5:
  2225.         dateString += ' 00:00:00 GMT'
  2226.     tm = rfc822.parsedate_tz(dateString)
  2227.     if tm:
  2228.         return time.gmtime(rfc822.mktime_tz(tm))
  2229. # rfc822.py defines several time zones, but we define some extra ones.
  2230. # 'ET' is equivalent to 'EST', etc.
  2231. _additional_timezones = {'AT': -400, 'ET': -500, 'CT': -600, 'MT': -700, 'PT': -800}
  2232. rfc822._timezones.update(_additional_timezones)
  2233. registerDateHandler(_parse_date_rfc822)    
  2234.  
  2235. def _parse_date(dateString):
  2236.     '''Parses a variety of date formats into a 9-tuple in GMT'''
  2237.     for handler in _date_handlers:
  2238.         try:
  2239.             date9tuple = handler(dateString)
  2240.             if not date9tuple: continue
  2241.             if len(date9tuple) != 9:
  2242.                 if _debug: sys.stderr.write('date handler function must return 9-tuple\n')
  2243.                 raise ValueError
  2244.             map(int, date9tuple)
  2245.             return date9tuple
  2246.         except Exception, e:
  2247.             if _debug: sys.stderr.write('%s raised %s\n' % (handler.__name__, repr(e)))
  2248.             pass
  2249.     return None
  2250.  
  2251. def _getCharacterEncoding(http_headers, xml_data):
  2252.     '''Get the character encoding of the XML document
  2253.  
  2254.     http_headers is a dictionary
  2255.     xml_data is a raw string (not Unicode)
  2256.     
  2257.     This is so much trickier than it sounds, it's not even funny.
  2258.     According to RFC 3023 ('XML Media Types'), if the HTTP Content-Type
  2259.     is application/xml, application/*+xml,
  2260.     application/xml-external-parsed-entity, or application/xml-dtd,
  2261.     the encoding given in the charset parameter of the HTTP Content-Type
  2262.     takes precedence over the encoding given in the XML prefix within the
  2263.     document, and defaults to 'utf-8' if neither are specified.  But, if
  2264.     the HTTP Content-Type is text/xml, text/*+xml, or
  2265.     text/xml-external-parsed-entity, the encoding given in the XML prefix
  2266.     within the document is ALWAYS IGNORED and only the encoding given in
  2267.     the charset parameter of the HTTP Content-Type header should be
  2268.     respected, and it defaults to 'us-ascii' if not specified.
  2269.  
  2270.     Furthermore, discussion on the atom-syntax mailing list with the
  2271.     author of RFC 3023 leads me to the conclusion that any document
  2272.     served with a Content-Type of text/* and no charset parameter
  2273.     must be treated as us-ascii.  (We now do this.)  And also that it
  2274.     must always be flagged as non-well-formed.  (We now do this too.)
  2275.     
  2276.     If Content-Type is unspecified (input was local file or non-HTTP source)
  2277.     or unrecognized (server just got it totally wrong), then go by the
  2278.     encoding given in the XML prefix of the document and default to
  2279.     'iso-8859-1' as per the HTTP specification (RFC 2616).
  2280.     
  2281.     Then, assuming we didn't find a character encoding in the HTTP headers
  2282.     (and the HTTP Content-type allowed us to look in the body), we need
  2283.     to sniff the first few bytes of the XML data and try to determine
  2284.     whether the encoding is ASCII-compatible.  Section F of the XML
  2285.     specification shows the way here:
  2286.     http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2287.  
  2288.     If the sniffed encoding is not ASCII-compatible, we need to make it
  2289.     ASCII compatible so that we can sniff further into the XML declaration
  2290.     to find the encoding attribute, which will tell us the true encoding.
  2291.  
  2292.     Of course, none of this guarantees that we will be able to parse the
  2293.     feed in the declared character encoding (assuming it was declared
  2294.     correctly, which many are not).  CJKCodecs and iconv_codec help a lot;
  2295.     you should definitely install them if you can.
  2296.     http://cjkpython.i18n.org/
  2297.     '''
  2298.  
  2299.     def _parseHTTPContentType(content_type):
  2300.         '''takes HTTP Content-Type header and returns (content type, charset)
  2301.  
  2302.         If no charset is specified, returns (content type, '')
  2303.         If no content type is specified, returns ('', '')
  2304.         Both return parameters are guaranteed to be lowercase strings
  2305.         '''
  2306.         content_type = content_type or ''
  2307.         content_type, params = cgi.parse_header(content_type)
  2308.         return content_type, params.get('charset', '').replace("'", '')
  2309.  
  2310.     sniffed_xml_encoding = ''
  2311.     xml_encoding = ''
  2312.     true_encoding = ''
  2313.     http_content_type, http_encoding = _parseHTTPContentType(http_headers.get('content-type'))
  2314.     # Must sniff for non-ASCII-compatible character encodings before
  2315.     # searching for XML declaration.  This heuristic is defined in
  2316.     # section F of the XML specification:
  2317.     # http://www.w3.org/TR/REC-xml/#sec-guessing-no-ext-info
  2318.     try:
  2319.         if xml_data[:4] == '\x4c\x6f\xa7\x94':
  2320.             # EBCDIC
  2321.             xml_data = _ebcdic_to_ascii(xml_data)
  2322.         elif xml_data[:4] == '\x00\x3c\x00\x3f':
  2323.             # UTF-16BE
  2324.             sniffed_xml_encoding = 'utf-16be'
  2325.             xml_data = unicode(xml_data, 'utf-16be').encode('utf-8')
  2326.         elif (len(xml_data) >= 4) and (xml_data[:2] == '\xfe\xff') and (xml_data[2:4] != '\x00\x00'):
  2327.             # UTF-16BE with BOM
  2328.             sniffed_xml_encoding = 'utf-16be'
  2329.             xml_data = unicode(xml_data[2:], 'utf-16be').encode('utf-8')
  2330.         elif xml_data[:4] == '\x3c\x00\x3f\x00':
  2331.             # UTF-16LE
  2332.             sniffed_xml_encoding = 'utf-16le'
  2333.             xml_data = unicode(xml_data, 'utf-16le').encode('utf-8')
  2334.         elif (len(xml_data) >= 4) and (xml_data[:2] == '\xff\xfe') and (xml_data[2:4] != '\x00\x00'):
  2335.             # UTF-16LE with BOM
  2336.             sniffed_xml_encoding = 'utf-16le'
  2337.             xml_data = unicode(xml_data[2:], 'utf-16le').encode('utf-8')
  2338.         elif xml_data[:4] == '\x00\x00\x00\x3c':
  2339.             # UTF-32BE
  2340.             sniffed_xml_encoding = 'utf-32be'
  2341.             xml_data = unicode(xml_data, 'utf-32be').encode('utf-8')
  2342.         elif xml_data[:4] == '\x3c\x00\x00\x00':
  2343.             # UTF-32LE
  2344.             sniffed_xml_encoding = 'utf-32le'
  2345.             xml_data = unicode(xml_data, 'utf-32le').encode('utf-8')
  2346.         elif xml_data[:4] == '\x00\x00\xfe\xff':
  2347.             # UTF-32BE with BOM
  2348.             sniffed_xml_encoding = 'utf-32be'
  2349.             xml_data = unicode(xml_data[4:], 'utf-32be').encode('utf-8')
  2350.         elif xml_data[:4] == '\xff\xfe\x00\x00':
  2351.             # UTF-32LE with BOM
  2352.             sniffed_xml_encoding = 'utf-32le'
  2353.             xml_data = unicode(xml_data[4:], 'utf-32le').encode('utf-8')
  2354.         elif xml_data[:3] == '\xef\xbb\xbf':
  2355.             # UTF-8 with BOM
  2356.             sniffed_xml_encoding = 'utf-8'
  2357.             xml_data = unicode(xml_data[3:], 'utf-8').encode('utf-8')
  2358.         else:
  2359.             # ASCII-compatible
  2360.             pass
  2361.         xml_encoding_match = re.compile('^<\?.*encoding=[\'"](.*?)[\'"].*\?>').match(xml_data)
  2362.     except:
  2363.         xml_encoding_match = None
  2364.     if xml_encoding_match:
  2365.         xml_encoding = xml_encoding_match.groups()[0].lower()
  2366.         if sniffed_xml_encoding and (xml_encoding in ('iso-10646-ucs-2', 'ucs-2', 'csunicode', 'iso-10646-ucs-4', 'ucs-4', 'csucs4', 'utf-16', 'utf-32', 'utf_16', 'utf_32', 'utf16', 'u16')):
  2367.             xml_encoding = sniffed_xml_encoding
  2368.     acceptable_content_type = 0
  2369.     application_content_types = ('application/xml', 'application/xml-dtd', 'application/xml-external-parsed-entity')
  2370.     text_content_types = ('text/xml', 'text/xml-external-parsed-entity')
  2371.     if (http_content_type in application_content_types) or \
  2372.        (http_content_type.startswith('application/') and http_content_type.endswith('+xml')):
  2373.         acceptable_content_type = 1
  2374.         true_encoding = http_encoding or xml_encoding or 'utf-8'
  2375.     elif (http_content_type in text_content_types) or \
  2376.          (http_content_type.startswith('text/')) and http_content_type.endswith('+xml'):
  2377.         acceptable_content_type = 1
  2378.         true_encoding = http_encoding or 'us-ascii'
  2379.     elif http_content_type.startswith('text/'):
  2380.         true_encoding = http_encoding or 'us-ascii'
  2381.     elif http_headers and (not http_headers.has_key('content-type')):
  2382.         true_encoding = xml_encoding or 'iso-8859-1'
  2383.     else:
  2384.         true_encoding = xml_encoding or 'utf-8'
  2385.     return true_encoding, http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type
  2386.     
  2387. def _toUTF8(data, encoding):
  2388.     '''Changes an XML data stream on the fly to specify a new encoding
  2389.  
  2390.     data is a raw sequence of bytes (not Unicode) that is presumed to be in %encoding already
  2391.     encoding is a string recognized by encodings.aliases
  2392.     '''
  2393.     if _debug: sys.stderr.write('entering _toUTF8, trying encoding %s\n' % encoding)
  2394.     # strip Byte Order Mark (if present)
  2395.     if (len(data) >= 4) and (data[:2] == '\xfe\xff') and (data[2:4] != '\x00\x00'):
  2396.         if _debug:
  2397.             sys.stderr.write('stripping BOM\n')
  2398.             if encoding != 'utf-16be':
  2399.                 sys.stderr.write('trying utf-16be instead\n')
  2400.         encoding = 'utf-16be'
  2401.         data = data[2:]
  2402.     elif (len(data) >= 4) and (data[:2] == '\xff\xfe') and (data[2:4] != '\x00\x00'):
  2403.         if _debug:
  2404.             sys.stderr.write('stripping BOM\n')
  2405.             if encoding != 'utf-16le':
  2406.                 sys.stderr.write('trying utf-16le instead\n')
  2407.         encoding = 'utf-16le'
  2408.         data = data[2:]
  2409.     elif data[:3] == '\xef\xbb\xbf':
  2410.         if _debug:
  2411.             sys.stderr.write('stripping BOM\n')
  2412.             if encoding != 'utf-8':
  2413.                 sys.stderr.write('trying utf-8 instead\n')
  2414.         encoding = 'utf-8'
  2415.         data = data[3:]
  2416.     elif data[:4] == '\x00\x00\xfe\xff':
  2417.         if _debug:
  2418.             sys.stderr.write('stripping BOM\n')
  2419.             if encoding != 'utf-32be':
  2420.                 sys.stderr.write('trying utf-32be instead\n')
  2421.         encoding = 'utf-32be'
  2422.         data = data[4:]
  2423.     elif data[:4] == '\xff\xfe\x00\x00':
  2424.         if _debug:
  2425.             sys.stderr.write('stripping BOM\n')
  2426.             if encoding != 'utf-32le':
  2427.                 sys.stderr.write('trying utf-32le instead\n')
  2428.         encoding = 'utf-32le'
  2429.         data = data[4:]
  2430.     newdata = unicode(data, encoding)
  2431.     if _debug: sys.stderr.write('successfully converted %s data to unicode\n' % encoding)
  2432.     declmatch = re.compile('^<\?xml[^>]*?>')
  2433.     newdecl = '''<?xml version='1.0' encoding='utf-8'?>'''
  2434.     if declmatch.search(newdata):
  2435.         newdata = declmatch.sub(newdecl, newdata)
  2436.     else:
  2437.         newdata = newdecl + u'\n' + newdata
  2438.     return newdata.encode('utf-8')
  2439.  
  2440. def _stripDoctype(data):
  2441.     '''Strips DOCTYPE from XML document, returns (rss_version, stripped_data)
  2442.  
  2443.     rss_version may be 'rss091n' or None
  2444.     stripped_data is the same XML document, minus the DOCTYPE
  2445.     '''
  2446.     entity_pattern = re.compile(r'<!ENTITY([^>]*?)>', re.MULTILINE)
  2447.     data = entity_pattern.sub('', data)
  2448.     doctype_pattern = re.compile(r'<!DOCTYPE([^>]*?)>', re.MULTILINE)
  2449.     doctype_results = doctype_pattern.findall(data)
  2450.     doctype = doctype_results and doctype_results[0] or ''
  2451.     if doctype.lower().count('netscape'):
  2452.         version = 'rss091n'
  2453.     else:
  2454.         version = None
  2455.     data = doctype_pattern.sub('', data)
  2456.     return version, data
  2457.     
  2458. def parse(url_file_stream_or_string, etag=None, modified=None, agent=None, referrer=None, handlers=[]):
  2459.     '''Parse a feed from a URL, file, stream, or string'''
  2460.     result = FeedParserDict()
  2461.     result['feed'] = FeedParserDict()
  2462.     result['entries'] = []
  2463.     if _XML_AVAILABLE:
  2464.         result['bozo'] = 0
  2465.     if type(handlers) == types.InstanceType:
  2466.         handlers = [handlers]
  2467.     try:
  2468.         f = _open_resource(url_file_stream_or_string, etag, modified, agent, referrer, handlers)
  2469.         data = f.read()
  2470.     except Exception, e:
  2471.         result['bozo'] = 1
  2472.         result['bozo_exception'] = e
  2473.         data = ''
  2474.         f = None
  2475.  
  2476.     # if feed is gzip-compressed, decompress it
  2477.     if f and data and hasattr(f, 'headers'):
  2478.         if gzip and f.headers.get('content-encoding', '') == 'gzip':
  2479.             try:
  2480.                 data = gzip.GzipFile(fileobj=_StringIO(data)).read()
  2481.             except Exception, e:
  2482.                 # Some feeds claim to be gzipped but they're not, so
  2483.                 # we get garbage.  Ideally, we should re-request the
  2484.                 # feed without the 'Accept-encoding: gzip' header,
  2485.                 # but we don't.
  2486.                 result['bozo'] = 1
  2487.                 result['bozo_exception'] = e
  2488.                 data = ''
  2489.         elif zlib and f.headers.get('content-encoding', '') == 'deflate':
  2490.             try:
  2491.                 data = zlib.decompress(data, -zlib.MAX_WBITS)
  2492.             except Exception, e:
  2493.                 result['bozo'] = 1
  2494.                 result['bozo_exception'] = e
  2495.                 data = ''
  2496.  
  2497.     # save HTTP headers
  2498.     if hasattr(f, 'info'):
  2499.         info = f.info()
  2500.         if info.has_key('Etag'):
  2501.             result['etag'] = info.getheader('ETag')
  2502.         last_modified = info.getheader('Last-Modified')
  2503.         if last_modified:
  2504.             result['modified'] = _parse_date(last_modified)
  2505.     if hasattr(f, 'url'):
  2506.         result['href'] = f.url
  2507.         result['status'] = 200
  2508.     if hasattr(f, 'status'):
  2509.         result['status'] = f.status
  2510.     if hasattr(f, 'headers'):
  2511.         result['headers'] = f.headers.dict
  2512.     if hasattr(f, 'close'):
  2513.         f.close()
  2514.  
  2515.     # there are four encodings to keep track of:
  2516.     # - http_encoding is the encoding declared in the Content-Type HTTP header
  2517.     # - xml_encoding is the encoding declared in the <?xml declaration
  2518.     # - sniffed_encoding is the encoding sniffed from the first 4 bytes of the XML data
  2519.     # - result['encoding'] is the actual encoding, as per RFC 3023 and a variety of other conflicting specifications
  2520.     http_headers = result.get('headers', {})
  2521.     result['encoding'], http_encoding, xml_encoding, sniffed_xml_encoding, acceptable_content_type = \
  2522.         _getCharacterEncoding(http_headers, data)
  2523.     if http_headers and (not acceptable_content_type):
  2524.         if http_headers.has_key('content-type'):
  2525.             bozo_message = '%s is not an XML media type' % http_headers['content-type']
  2526.         else:
  2527.             bozo_message = 'no Content-type specified'
  2528.         result['bozo'] = 1
  2529.         result['bozo_exception'] = NonXMLContentType(bozo_message)
  2530.         
  2531.     result['version'], data = _stripDoctype(data)
  2532.  
  2533.     baseuri = http_headers.get('content-location', result.get('href'))
  2534.     baselang = http_headers.get('content-language', None)
  2535.  
  2536.     # if server sent 304, we're done
  2537.     if result.get('status', 0) == 304:
  2538.         result['version'] = ''
  2539.         result['debug_message'] = 'The feed has not changed since you last checked, ' + \
  2540.             'so the server sent no data.  This is a feature, not a bug!'
  2541.         return result
  2542.  
  2543.     # if there was a problem downloading, we're done
  2544.     if not data:
  2545.         return result
  2546.  
  2547.     # determine character encoding
  2548.     use_strict_parser = 0
  2549.     known_encoding = 0
  2550.     tried_encodings = []
  2551.     # try: HTTP encoding, declared XML encoding, encoding sniffed from BOM
  2552.     for proposed_encoding in (result['encoding'], xml_encoding, sniffed_xml_encoding):
  2553.         if not proposed_encoding: continue
  2554.         if proposed_encoding in tried_encodings: continue
  2555.         tried_encodings.append(proposed_encoding)
  2556.         try:
  2557.             data = _toUTF8(data, proposed_encoding)
  2558.             known_encoding = use_strict_parser = 1
  2559.             break
  2560.         except:
  2561.             pass
  2562.     # if no luck and we have auto-detection library, try that
  2563.     if (not known_encoding) and chardet:
  2564.         try:
  2565.             proposed_encoding = chardet.detect(data)['encoding']
  2566.             if proposed_encoding and (proposed_encoding not in tried_encodings):
  2567.                 tried_encodings.append(proposed_encoding)
  2568.                 data = _toUTF8(data, proposed_encoding)
  2569.                 known_encoding = use_strict_parser = 1
  2570.         except:
  2571.             pass
  2572.     # if still no luck and we haven't tried utf-8 yet, try that
  2573.     if (not known_encoding) and ('utf-8' not in tried_encodings):
  2574.         try:
  2575.             proposed_encoding = 'utf-8'
  2576.             tried_encodings.append(proposed_encoding)
  2577.             data = _toUTF8(data, proposed_encoding)
  2578.             known_encoding = use_strict_parser = 1
  2579.         except:
  2580.             pass
  2581.     # if still no luck and we haven't tried windows-1252 yet, try that
  2582.     if (not known_encoding) and ('windows-1252' not in tried_encodings):
  2583.         try:
  2584.             proposed_encoding = 'windows-1252'
  2585.             tried_encodings.append(proposed_encoding)
  2586.             data = _toUTF8(data, proposed_encoding)
  2587.             known_encoding = use_strict_parser = 1
  2588.         except:
  2589.             pass
  2590.     # if still no luck, give up
  2591.     if not known_encoding:
  2592.         result['bozo'] = 1
  2593.         result['bozo_exception'] = CharacterEncodingUnknown( \
  2594.             'document encoding unknown, I tried ' + \
  2595.             '%s, %s, utf-8, and windows-1252 but nothing worked' % \
  2596.             (result['encoding'], xml_encoding))
  2597.         result['encoding'] = ''
  2598.     elif proposed_encoding != result['encoding']:
  2599.         result['bozo'] = 1
  2600.         result['bozo_exception'] = CharacterEncodingOverride( \
  2601.             'documented declared as %s, but parsed as %s' % \
  2602.             (result['encoding'], proposed_encoding))
  2603.         result['encoding'] = proposed_encoding
  2604.  
  2605.     if not _XML_AVAILABLE:
  2606.         use_strict_parser = 0
  2607.     if use_strict_parser:
  2608.         # initialize the SAX parser
  2609.         feedparser = _StrictFeedParser(baseuri, baselang, 'utf-8')
  2610.         saxparser = xml.sax.make_parser(PREFERRED_XML_PARSERS)
  2611.         saxparser.setFeature(xml.sax.handler.feature_namespaces, 1)
  2612.         saxparser.setContentHandler(feedparser)
  2613.         saxparser.setErrorHandler(feedparser)
  2614.         source = xml.sax.xmlreader.InputSource()
  2615.         source.setByteStream(_StringIO(data))
  2616.         if hasattr(saxparser, '_ns_stack'):
  2617.             # work around bug in built-in SAX parser (doesn't recognize xml: namespace)
  2618.             # PyXML doesn't have this problem, and it doesn't have _ns_stack either
  2619.             saxparser._ns_stack.append({'http://www.w3.org/XML/1998/namespace':'xml'})
  2620.         try:
  2621.             saxparser.parse(source)
  2622.         except Exception, e:
  2623.             if _debug:
  2624.                 import traceback
  2625.                 traceback.print_stack()
  2626.                 traceback.print_exc()
  2627.                 sys.stderr.write('xml parsing failed\n')
  2628.             result['bozo'] = 1
  2629.             result['bozo_exception'] = feedparser.exc or e
  2630.             use_strict_parser = 0
  2631.     if not use_strict_parser:
  2632.         feedparser = _LooseFeedParser(baseuri, baselang, known_encoding and 'utf-8' or '')
  2633.         feedparser.feed(data)
  2634.     result['feed'] = feedparser.feeddata
  2635.     result['entries'] = feedparser.entries
  2636.     result['version'] = result['version'] or feedparser.version
  2637.     result['namespaces'] = feedparser.namespacesInUse
  2638.     return result
  2639.  
  2640. if __name__ == '__main__':
  2641.     if not sys.argv[1:]:
  2642.         print __doc__
  2643.         sys.exit(0)
  2644.     else:
  2645.         urls = sys.argv[1:]
  2646.     zopeCompatibilityHack()
  2647.     from pprint import pprint
  2648.     for url in urls:
  2649.         print url
  2650.         print
  2651.         result = parse(url)
  2652.         pprint(result)
  2653.         print
  2654.  
  2655. #REVISION HISTORY
  2656. #1.0 - 9/27/2002 - MAP - fixed namespace processing on prefixed RSS 2.0 elements,
  2657. #  added Simon Fell's test suite
  2658. #1.1 - 9/29/2002 - MAP - fixed infinite loop on incomplete CDATA sections
  2659. #2.0 - 10/19/2002
  2660. #  JD - use inchannel to watch out for image and textinput elements which can
  2661. #  also contain title, link, and description elements
  2662. #  JD - check for isPermaLink='false' attribute on guid elements
  2663. #  JD - replaced openAnything with open_resource supporting ETag and
  2664. #  If-Modified-Since request headers
  2665. #  JD - parse now accepts etag, modified, agent, and referrer optional
  2666. #  arguments
  2667. #  JD - modified parse to return a dictionary instead of a tuple so that any
  2668. #  etag or modified information can be returned and cached by the caller
  2669. #2.0.1 - 10/21/2002 - MAP - changed parse() so that if we don't get anything
  2670. #  because of etag/modified, return the old etag/modified to the caller to
  2671. #  indicate why nothing is being returned
  2672. #2.0.2 - 10/21/2002 - JB - added the inchannel to the if statement, otherwise its
  2673. #  useless.  Fixes the problem JD was addressing by adding it.
  2674. #2.1 - 11/14/2002 - MAP - added gzip support
  2675. #2.2 - 1/27/2003 - MAP - added attribute support, admin:generatorAgent.
  2676. #  start_admingeneratoragent is an example of how to handle elements with
  2677. #  only attributes, no content.
  2678. #2.3 - 6/11/2003 - MAP - added USER_AGENT for default (if caller doesn't specify);
  2679. #  also, make sure we send the User-Agent even if urllib2 isn't available.
  2680. #  Match any variation of backend.userland.com/rss namespace.
  2681. #2.3.1 - 6/12/2003 - MAP - if item has both link and guid, return both as-is.
  2682. #2.4 - 7/9/2003 - MAP - added preliminary Pie/Atom/Echo support based on Sam Ruby's
  2683. #  snapshot of July 1 <http://www.intertwingly.net/blog/1506.html>; changed
  2684. #  project name
  2685. #2.5 - 7/25/2003 - MAP - changed to Python license (all contributors agree);
  2686. #  removed unnecessary urllib code -- urllib2 should always be available anyway;
  2687. #  return actual url, status, and full HTTP headers (as result['url'],
  2688. #  result['status'], and result['headers']) if parsing a remote feed over HTTP --
  2689. #  this should pass all the HTTP tests at <http://diveintomark.org/tests/client/http/>;
  2690. #  added the latest namespace-of-the-week for RSS 2.0
  2691. #2.5.1 - 7/26/2003 - RMK - clear opener.addheaders so we only send our custom
  2692. #  User-Agent (otherwise urllib2 sends two, which confuses some servers)
  2693. #2.5.2 - 7/28/2003 - MAP - entity-decode inline xml properly; added support for
  2694. #  inline <xhtml:body> and <xhtml:div> as used in some RSS 2.0 feeds
  2695. #2.5.3 - 8/6/2003 - TvdV - patch to track whether we're inside an image or
  2696. #  textInput, and also to return the character encoding (if specified)
  2697. #2.6 - 1/1/2004 - MAP - dc:author support (MarekK); fixed bug tracking
  2698. #  nested divs within content (JohnD); fixed missing sys import (JohanS);
  2699. #  fixed regular expression to capture XML character encoding (Andrei);
  2700. #  added support for Atom 0.3-style links; fixed bug with textInput tracking;
  2701. #  added support for cloud (MartijnP); added support for multiple
  2702. #  category/dc:subject (MartijnP); normalize content model: 'description' gets
  2703. #  description (which can come from description, summary, or full content if no
  2704. #  description), 'content' gets dict of base/language/type/value (which can come
  2705. #  from content:encoded, xhtml:body, content, or fullitem);
  2706. #  fixed bug matching arbitrary Userland namespaces; added xml:base and xml:lang
  2707. #  tracking; fixed bug tracking unknown tags; fixed bug tracking content when
  2708. #  <content> element is not in default namespace (like Pocketsoap feed);
  2709. #  resolve relative URLs in link, guid, docs, url, comments, wfw:comment,
  2710. #  wfw:commentRSS; resolve relative URLs within embedded HTML markup in
  2711. #  description, xhtml:body, content, content:encoded, title, subtitle,
  2712. #  summary, info, tagline, and copyright; added support for pingback and
  2713. #  trackback namespaces
  2714. #2.7 - 1/5/2004 - MAP - really added support for trackback and pingback
  2715. #  namespaces, as opposed to 2.6 when I said I did but didn't really;
  2716. #  sanitize HTML markup within some elements; added mxTidy support (if
  2717. #  installed) to tidy HTML markup within some elements; fixed indentation
  2718. #  bug in _parse_date (FazalM); use socket.setdefaulttimeout if available
  2719. #  (FazalM); universal date parsing and normalization (FazalM): 'created', modified',
  2720. #  'issued' are parsed into 9-tuple date format and stored in 'created_parsed',
  2721. #  'modified_parsed', and 'issued_parsed'; 'date' is duplicated in 'modified'
  2722. #  and vice-versa; 'date_parsed' is duplicated in 'modified_parsed' and vice-versa
  2723. #2.7.1 - 1/9/2004 - MAP - fixed bug handling " and '.  fixed memory
  2724. #  leak not closing url opener (JohnD); added dc:publisher support (MarekK);
  2725. #  added admin:errorReportsTo support (MarekK); Python 2.1 dict support (MarekK)
  2726. #2.7.4 - 1/14/2004 - MAP - added workaround for improperly formed <br/> tags in
  2727. #  encoded HTML (skadz); fixed unicode handling in normalize_attrs (ChrisL);
  2728. #  fixed relative URI processing for guid (skadz); added ICBM support; added
  2729. #  base64 support
  2730. #2.7.5 - 1/15/2004 - MAP - added workaround for malformed DOCTYPE (seen on many
  2731. #  blogspot.com sites); added _debug variable
  2732. #2.7.6 - 1/16/2004 - MAP - fixed bug with StringIO importing
  2733. #3.0b3 - 1/23/2004 - MAP - parse entire feed with real XML parser (if available);
  2734. #  added several new supported namespaces; fixed bug tracking naked markup in
  2735. #  description; added support for enclosure; added support for source; re-added
  2736. #  support for cloud which got dropped somehow; added support for expirationDate
  2737. #3.0b4 - 1/26/2004 - MAP - fixed xml:lang inheritance; fixed multiple bugs tracking
  2738. #  xml:base URI, one for documents that don't define one explicitly and one for
  2739. #  documents that define an outer and an inner xml:base that goes out of scope
  2740. #  before the end of the document
  2741. #3.0b5 - 1/26/2004 - MAP - fixed bug parsing multiple links at feed level
  2742. #3.0b6 - 1/27/2004 - MAP - added feed type and version detection, result['version']
  2743. #  will be one of SUPPORTED_VERSIONS.keys() or empty string if unrecognized;
  2744. #  added support for creativeCommons:license and cc:license; added support for
  2745. #  full Atom content model in title, tagline, info, copyright, summary; fixed bug
  2746. #  with gzip encoding (not always telling server we support it when we do)
  2747. #3.0b7 - 1/28/2004 - MAP - support Atom-style author element in author_detail
  2748. #  (dictionary of 'name', 'url', 'email'); map author to author_detail if author
  2749. #  contains name + email address
  2750. #3.0b8 - 1/28/2004 - MAP - added support for contributor
  2751. #3.0b9 - 1/29/2004 - MAP - fixed check for presence of dict function; added
  2752. #  support for summary
  2753. #3.0b10 - 1/31/2004 - MAP - incorporated ISO-8601 date parsing routines from
  2754. #  xml.util.iso8601
  2755. #3.0b11 - 2/2/2004 - MAP - added 'rights' to list of elements that can contain
  2756. #  dangerous markup; fiddled with decodeEntities (not right); liberalized
  2757. #  date parsing even further
  2758. #3.0b12 - 2/6/2004 - MAP - fiddled with decodeEntities (still not right);
  2759. #  added support to Atom 0.2 subtitle; added support for Atom content model
  2760. #  in copyright; better sanitizing of dangerous HTML elements with end tags
  2761. #  (script, frameset)
  2762. #3.0b13 - 2/8/2004 - MAP - better handling of empty HTML tags (br, hr, img,
  2763. #  etc.) in embedded markup, in either HTML or XHTML form (<br>, <br/>, <br />)
  2764. #3.0b14 - 2/8/2004 - MAP - fixed CDATA handling in non-wellformed feeds under
  2765. #  Python 2.1
  2766. #3.0b15 - 2/11/2004 - MAP - fixed bug resolving relative links in wfw:commentRSS;
  2767. #  fixed bug capturing author and contributor URL; fixed bug resolving relative
  2768. #  links in author and contributor URL; fixed bug resolvin relative links in
  2769. #  generator URL; added support for recognizing RSS 1.0; passed Simon Fell's
  2770. #  namespace tests, and included them permanently in the test suite with his
  2771. #  permission; fixed namespace handling under Python 2.1
  2772. #3.0b16 - 2/12/2004 - MAP - fixed support for RSS 0.90 (broken in b15)
  2773. #3.0b17 - 2/13/2004 - MAP - determine character encoding as per RFC 3023
  2774. #3.0b18 - 2/17/2004 - MAP - always map description to summary_detail (Andrei);
  2775. #  use libxml2 (if available)
  2776. #3.0b19 - 3/15/2004 - MAP - fixed bug exploding author information when author
  2777. #  name was in parentheses; removed ultra-problematic mxTidy support; patch to
  2778. #  workaround crash in PyXML/expat when encountering invalid entities
  2779. #  (MarkMoraes); support for textinput/textInput
  2780. #3.0b20 - 4/7/2004 - MAP - added CDF support
  2781. #3.0b21 - 4/14/2004 - MAP - added Hot RSS support
  2782. #3.0b22 - 4/19/2004 - MAP - changed 'channel' to 'feed', 'item' to 'entries' in
  2783. #  results dict; changed results dict to allow getting values with results.key
  2784. #  as well as results[key]; work around embedded illformed HTML with half
  2785. #  a DOCTYPE; work around malformed Content-Type header; if character encoding
  2786. #  is wrong, try several common ones before falling back to regexes (if this
  2787. #  works, bozo_exception is set to CharacterEncodingOverride); fixed character
  2788. #  encoding issues in BaseHTMLProcessor by tracking encoding and converting
  2789. #  from Unicode to raw strings before feeding data to sgmllib.SGMLParser;
  2790. #  convert each value in results to Unicode (if possible), even if using
  2791. #  regex-based parsing
  2792. #3.0b23 - 4/21/2004 - MAP - fixed UnicodeDecodeError for feeds that contain
  2793. #  high-bit characters in attributes in embedded HTML in description (thanks
  2794. #  Thijs van de Vossen); moved guid, date, and date_parsed to mapped keys in
  2795. #  FeedParserDict; tweaked FeedParserDict.has_key to return True if asking
  2796. #  about a mapped key
  2797. #3.0fc1 - 4/23/2004 - MAP - made results.entries[0].links[0] and
  2798. #  results.entries[0].enclosures[0] into FeedParserDict; fixed typo that could
  2799. #  cause the same encoding to be tried twice (even if it failed the first time);
  2800. #  fixed DOCTYPE stripping when DOCTYPE contained entity declarations;
  2801. #  better textinput and image tracking in illformed RSS 1.0 feeds
  2802. #3.0fc2 - 5/10/2004 - MAP - added and passed Sam's amp tests; added and passed
  2803. #  my blink tag tests
  2804. #3.0fc3 - 6/18/2004 - MAP - fixed bug in _changeEncodingDeclaration that
  2805. #  failed to parse utf-16 encoded feeds; made source into a FeedParserDict;
  2806. #  duplicate admin:generatorAgent/@rdf:resource in generator_detail.url;
  2807. #  added support for image; refactored parse() fallback logic to try other
  2808. #  encodings if SAX parsing fails (previously it would only try other encodings
  2809. #  if re-encoding failed); remove unichr madness in normalize_attrs now that
  2810. #  we're properly tracking encoding in and out of BaseHTMLProcessor; set
  2811. #  feed.language from root-level xml:lang; set entry.id from rdf:about;
  2812. #  send Accept header
  2813. #3.0 - 6/21/2004 - MAP - don't try iso-8859-1 (can't distinguish between
  2814. #  iso-8859-1 and windows-1252 anyway, and most incorrectly marked feeds are
  2815. #  windows-1252); fixed regression that could cause the same encoding to be
  2816. #  tried twice (even if it failed the first time)
  2817. #3.0.1 - 6/22/2004 - MAP - default to us-ascii for all text/* content types;
  2818. #  recover from malformed content-type header parameter with no equals sign
  2819. #  ('text/xml; charset:iso-8859-1')
  2820. #3.1 - 6/28/2004 - MAP - added and passed tests for converting HTML entities
  2821. #  to Unicode equivalents in illformed feeds (aaronsw); added and
  2822. #  passed tests for converting character entities to Unicode equivalents
  2823. #  in illformed feeds (aaronsw); test for valid parsers when setting
  2824. #  XML_AVAILABLE; make version and encoding available when server returns
  2825. #  a 304; add handlers parameter to pass arbitrary urllib2 handlers (like
  2826. #  digest auth or proxy support); add code to parse username/password
  2827. #  out of url and send as basic authentication; expose downloading-related
  2828. #  exceptions in bozo_exception (aaronsw); added __contains__ method to
  2829. #  FeedParserDict (aaronsw); added publisher_detail (aaronsw)
  2830. #3.2 - 7/3/2004 - MAP - use cjkcodecs and iconv_codec if available; always
  2831. #  convert feed to UTF-8 before passing to XML parser; completely revamped
  2832. #  logic for determining character encoding and attempting XML parsing
  2833. #  (much faster); increased default timeout to 20 seconds; test for presence
  2834. #  of Location header on redirects; added tests for many alternate character
  2835. #  encodings; support various EBCDIC encodings; support UTF-16BE and
  2836. #  UTF16-LE with or without a BOM; support UTF-8 with a BOM; support
  2837. #  UTF-32BE and UTF-32LE with or without a BOM; fixed crashing bug if no
  2838. #  XML parsers are available; added support for 'Content-encoding: deflate';
  2839. #  send blank 'Accept-encoding: ' header if neither gzip nor zlib modules
  2840. #  are available
  2841. #3.3 - 7/15/2004 - MAP - optimize EBCDIC to ASCII conversion; fix obscure
  2842. #  problem tracking xml:base and xml:lang if element declares it, child
  2843. #  doesn't, first grandchild redeclares it, and second grandchild doesn't;
  2844. #  refactored date parsing; defined public registerDateHandler so callers
  2845. #  can add support for additional date formats at runtime; added support
  2846. #  for OnBlog, Nate, MSSQL, Greek, and Hungarian dates (ytrewq1); added
  2847. #  zopeCompatibilityHack() which turns FeedParserDict into a regular
  2848. #  dictionary, required for Zope compatibility, and also makes command-
  2849. #  line debugging easier because pprint module formats real dictionaries
  2850. #  better than dictionary-like objects; added NonXMLContentType exception,
  2851. #  which is stored in bozo_exception when a feed is served with a non-XML
  2852. #  media type such as 'text/plain'; respect Content-Language as default
  2853. #  language if not xml:lang is present; cloud dict is now FeedParserDict;
  2854. #  generator dict is now FeedParserDict; better tracking of xml:lang,
  2855. #  including support for xml:lang='' to unset the current language;
  2856. #  recognize RSS 1.0 feeds even when RSS 1.0 namespace is not the default
  2857. #  namespace; don't overwrite final status on redirects (scenarios:
  2858. #  redirecting to a URL that returns 304, redirecting to a URL that
  2859. #  redirects to another URL with a different type of redirect); add
  2860. #  support for HTTP 303 redirects
  2861. #4.0 - MAP - support for relative URIs in xml:base attribute; fixed
  2862. #  encoding issue with mxTidy (phopkins); preliminary support for RFC 3229;
  2863. #  support for Atom 1.0; support for iTunes extensions; new 'tags' for
  2864. #  categories/keywords/etc. as array of dict
  2865. #  {'term': term, 'scheme': scheme, 'label': label} to match Atom 1.0
  2866. #  terminology; parse RFC 822-style dates with no time; lots of other
  2867. #  bug fixes
  2868. #4.1 - MAP - removed socket timeout; added support for chardet library
  2869.